<?php error_reporting(E_ALL | E_NOTICE | E_STRICT);
$GLOBALS['start_time'] = microtime(true);?><?php

class CCache{
	private $cache;function __construct(){}function cache_file_name($fn){return CFile('publish/'.(CPortal::$current?portal()->id:CPortal::$default).'/cache')->mkdir().'/'.preg_replace('/[^a-zA-Z0-9_-]/','_',$fn).'.cache';}function &set($key, $var, $expired = false){$this->cache[$key] = $var;file_put_contents($this->cache_file_name($key),$var);return $this;}
	function &delete($key, $timeout=0){if(isset($this->cache[$key])){unset($this->cache[$key]);}$fn = $this->cache_file_name($key);if(CFile::exists($fn)){unlink($fn);}return $this;}
	function get($key){if(isset($this->cache[$key])){return $this->cache[$key];}$fn = $this->cache_file_name($key);if(CFile::exists($fn)){$this->data[$key] = file_get_contents($fn);return $this->data[$key];}return '';}
	function &flush(){$this->cache = array();if(CPortal::$current){CFile('publish/'.portal()->id.'/cache')->delete();}CFile('publish/'.CPortal::$default.'/cache')->delete();return $this;}}function cache($key = NULL, $value = NULL){if($key){if($value !== NULL){CSystem::$cache->set($key, $value);}else{return CSystem::$cache->get($key);}}}?><?php

class CMemCache extends CCache{
	public $connected_servers = array();public $connected_hosts = array();public $selected_ip = false;
	function __construct($servers){$this->servers = $servers;if(!$this->connected_servers){$this->connected_servers = array();foreach($servers as $server){if($con = memcache_pconnect($server['host'], isset($server['port'])?$server['port']:11211)){$this->connected_servers[] = $con;$this->connected_hosts[$server['host']] = sizeof($this->connected_hosts);}}}}function &server($key){$sizeof = sizeof($this->connected_servers);if($sizeof==1){return $this->connected_servers[0];}else{if($ip = $this->selected_ip){$this->selected_ip = false;if(isset($this->connected_hosts[$ip])){return $this->connected_servers[$this->connected_hosts[$ip]];}}return $this->connected_servers[(crc32($key) & 0x7fffffff)%$sizeof];}}function &select_server($ip){$this->selected_ip = $ip;return $this;}
	function &set($key, $var, $expired = 600){$result = $this->server($key)->replace( $_SERVER['SERVER_NAME'].$key, $var, 0, $expired);if( $result === false ){$result = $this->server($key)->set($_SERVER['SERVER_NAME'].$key, $var, 0, $expired);}return $this;}
	function &delete($key, $timeout = 0){$this->server($key)->delete($_SERVER['SERVER_NAME'].$key, $timeout);return $this;}
	function get($key){return $this->server($key)->get($_SERVER['SERVER_NAME'].$key);}
	function &flush(){for($i=0; $i<sizeof($this->connected_servers);$i++){$this->connected_servers[$i]->flush();}return $this;}}
function CMemCache($host, $port = 11211, $timeout = 1){return new CMemCache($host, $port, $timeout);}?><?php

class CDataXmlStore extends CXmlStore{function __construct($file_name, $root_query = ''){parent::__construct($file_name, $root_query);}function select_all($table, $conditions = false, $options = array()){if($table === false and !$this->loaded){if($file = CTable('file')->fields('id, php_array')->select($this->file_name) and $file['php_array']){eval('$result = '.$file['php_array'].';');
				return $result;}}return parent::select_all($table, $conditions, $options);}function save(){if($this->file_name){if(portal()->setting('data-xml') == 'database'){if($file = CTable('file')->fields('id')->select($this->file_name)){CTable('file')->update(array(
						'content' => $this->xml->doc->saveXML(),
						'php_array' => var_export($this->xml->decode(),1),
					), $this->file_name);}else{CTable('file')->insert(array(
						'id'=>$this->file_name, 
						'content' => $this->xml->doc->saveXML(),
						'php_array' => var_export($this->xml->decode(),1),
					));}}else{$this->xml->save((USE_FTP?FTP_PREFIX:'').$this->file_name);}}}function load(){if($this->file_name){if(portal()->setting('data-xml') == 'database'){if($file = CTable('file')->fields('id, content')->select($this->file_name)){$this->xml->doc->loadXML($file['content']);}else{$file_name = str_replace(ROOT_DIR,'',str_replace('%5C','/',$this->file_name));
					if(CFile::exists($file_name)){$this->xml->doc->load($file_name);
						CTable('file')->insert(array(
							'id'=>$this->file_name, 
							'content' => $this->xml->doc->saveXML(),
							'php_array' => var_export($this->xml->decode(),1),
						));}}}else{if(!$this->loaded){$this->xml->load((USE_FTP?FTP_PREFIX:'').$this->file_name);
					$this->loaded = true;}}}}}
function CDataXmlStore($file_name, $root_query = ''){return new CDataXmlStore($file_name, $root_query);}?><?php

class CFile{
	public static $ftp_connection_id = false;
	public $file_name;
	
	public $id;
	
	function __construct($file_name){$this->file_name = $file_name;}
	function &close(){try{if($this->id){fclose($this->id);
				$this->id = false;}}catch(Exception $e){}}
	function &open($mode = 'r'){try{$this->id = fopen($this->file_name, $mode);}catch(Exception $e){}return $this;}
	function get(){try{return file_get_contents($this->file_name);}catch(Exception $e){}}
	function &put($content){try{file_put_contents($this->file_name, $content);}catch(Exception $e){}return $this;}
	function &seek($pos, $whence = SEEK_SET){try{fseek($this->id, $pos, $whence);}catch(Exception $e){}return $this;}
	function eof(){try{return feof($this->id);}catch(Exception $e){}return true;}
	function files(){$files = array();
		if(is_dir($this->file_name)){$dir = opendir($this->file_name);
			while($file = readdir($dir)){if($file != '.' and $file != '..'){$files[$file] = $file;}}}return $files;}
	static function remove($filename, $upload_dir = ""){if(CFile::exists($upload_dir . $filename)){return @unlink($upload_dir . $filename);}else{return false;}}function mkdir(){$dir_arr  = explode('/',$this->file_name);
		if(strpos($this->file_name, 'ftp://') !== false){$start_pos = 3;
			$dir = 'ftp://'.$dir_arr[2].'/'.$dir_arr[3];}else{$start_pos = 0;
			$dir = $dir_arr[0];}for ($i = $start_pos; $i<count($dir_arr); $i++){if(!is_dir($dir)){mkdir($dir);}if($i<count($dir_arr)-1){$dir = $dir.'/'.$dir_arr[$i+1];}}return $this->file_name;}function delete($path = false, $remove = false){if(!$path){$path = $this->file_name;}if(is_dir($path)){$dir = opendir($path);
			while($file = readdir($dir)){if($file != '.' and $file != '..'){$this->delete($path.'/'.$file,true);}}closedir($dir);
			if($remove){rmdir($path);}}elseif(CFile::exists($path)){unlink($path);}}public static function exists($url){if (null === $url || '' === trim($url)){return false;}if(preg_match('/^ftp|ftps/',$url)){$url = str_replace(FTP_PREFIX, '', $url);
			$exists = ftp_size(CFile::ftp_connection_id(), $url)>0;
			return $exists;}else{return file_exists($url);}}static public function ftp_connection_id(){if(!CFile::$ftp_connection_id){CFile::$ftp_connection_id = ftp_connect(FTP_HOST);
			ftp_login(CFile::$ftp_connection_id, FTP_USER, FTP_PASSWORD);
			ftp_pasv (CFile::$ftp_connection_id, true);}return CFile::$ftp_connection_id;}static function ftp_fput($file_name, $content = false){$file_name = str_replace(FTP_PREFIX, '', $file_name);
		if($content){CFile(substr($file_name, 0, strrpos($file_name, '/')))->mkdir();
			file_put_contents($file_name, $content);}$ret = ftp_nb_put(CFile::ftp_connection_id(), $file_name, $file_name, FTP_BINARY);
		while ($ret == FTP_MOREDATA){$ret = ftp_nb_continue(CFile::ftp_connection_id());}}}
function CFile($file_name=false){return new CFile($file_name);}?><?php

class CMySQLStore extends CStore{
	public $id = false;
	
	public $host;
	
	public $username;
	
	public $password;
	
	public $database;
	public $slave_id = false;
	
	public $slave_host;
	
	public $slave_username;
	
	public $slave_password;
	public $slave_database;
	public $slave_connected = false;
	public static $cache = array();
	
	function __construct($host, $username, $password, $database, $slave_host = false, $slave_username = false, $slave_password = false, $slave_database = false){$this->host = $host;
		$this->username = $username;
		$this->password = $password;
		$this->database = $database;
		$this->slave_host = $slave_host?$slave_host:$host;
		$this->slave_username = $slave_username?$slave_username:$username;
		$this->slave_password = ($slave_password!==false)?$slave_password:$password;
		$this->slave_database = $slave_database?$slave_database:$database;}
	function connect(){if(!$this->connected){if($this->id = mysql_connect($this->host, $this->username, $this->password)){mysql_select_db($this->database);
				$this->connected = true;
				if($this->slave_host == $this->host and $this->slave_database == $this->database){$this->slave_id = $this->id;
					$this->slave_connected = true;}}else{$this->connected = true;}}}function slave_connect(){if($this->slave_host != $this->host or $this->slave_database != $this->database){if(!$this->slave_connected){$connect_func = 'mysql_'.(portal()->setting('mysql-slave-persistent-connection')?'p':'').'connect';
				if($this->slave_id = $connect_func($this->slave_host, $this->slave_username, $this->slave_password)){mysql_select_db($this->database);
					$this->slave_connected = true;}else{echo '<script>location="http://error.vimua.com/";</script>';
					CSystem::end();}}}else{$this->connect();}}
	function close(){if($this->connected){mysql_close($this->id);
			$this->connected = false;}if(!portal()->setting('mysql-slave-persistent-connection')){if(($this->slave_host != $this->host  or $this->slave_database != $this->database) and $this->slave_connected){mysql_close($this->slave_id);}$this->slave_connected = false;}}
	function select($table, $conditions = false, $options = array()){$condition_string = $this->condition_string($conditions);
		if(!isset($options['items_per_page']) and isset(CMySQLStore::$cache[$table.':'.$condition_string])){return CMySQLStore::$cache[$table.':'.$condition_string];}$slave = isset($options['slave'])?$options['slave']:true;
		if($slave){$this->slave_connect();}else{$this->connect();}$options = array_merge(array(
			'fields'=>'*', 
			'order_by' => false, 
			'order_type'=>'',
			'page_no' => 1, 
			'items_per_page' => 1000
		),$options);
		if(is_array($options['fields'])){$fields_string = '`'.join('`,`',$options['fields']).'`';}else{$fields_string = $options['fields'];}$query ='
			SELECT
				'.$fields_string.'
			FROM
				`'.$table.'`
			'.($condition_string?'
			WHERE
				'.$this->condition_string($conditions):'').'
			'.($options['order_by']?' ORDER BY '.$options['order_by'].' '.$options['order_type']:'').'
			LIMIT
				'.(($options['page_no']-1)*$options['items_per_page']).','.$options['items_per_page'].'
		';
		$item = $this->fetch($query, $slave);
		CMySQLStore::$cache[$table.':'.$condition_string] = $item;
		return $item;}
	function count($table, $conditions=false){$this->slave_connect();
		$condition_string = $this->condition_string($conditions);
		$row = $this->fetch('
			SELECT
				count(*) as total
			FROM
				`'.$table.'`
			'.($condition_string?'
			WHERE
				'.$this->condition_string($conditions):'').'
		', true);
		return $row['total'];}function sum($field_name,$table, $conditions=false){return $this->math_fn('sum',$field_name,$table,$conditions);}
	function math_fn($math_fn, $fieldname, $table, $conditions=false){$this->slave_connect();
		$condition_string = $this->condition_string($conditions);
		$query = '
			SELECT '.$math_fn.
				'(`'.$fieldname.'`) as result
			FROM
				`'.$table.'`
			'.($condition_string?'
			WHERE
				'.$this->condition_string($conditions):'').'
		';
		$row = $this->fetch($query, true);
		return $row['result'];}
	function query($query_string, $slave = false){if(DEBUG){CLog()->log('QUERY',$query_string);}try{if($slave?$this->slave_id:$this->id){$result = mysql_query($query_string,$slave?$this->slave_id:$this->id);}else{return false;}}catch(Exception $e){return false;}return $result;}function fetch($query_string = false, $slave = false){try{if(!$query_string){return mysql_fetch_assoc($this->result);}elseif($this->result = $this->query($query_string, $slave)){return mysql_fetch_assoc($this->result);}}catch(Exception $e){}}
	function insert($table, $values){$this->connect();
		$query='insert into';
		$query.=' `'.$table.'`(';
		$i=0;
		if(is_array($values)){foreach($values as $key=>$value){if(($key===0) or is_numeric($key)){$key=$value;}if($key){if($i<>0){$query.=',';}$query.='`'.$key.'`';
					$i++;}}$query.=') values(';
			$i=0;
			foreach($values as $key=>$value){if(is_numeric($key) or $key===0){$value=Url::get($value);}if($i<>0){$query.=',';}if($value==='NULL'){$query.='NULL';}else{$query.='\''.(is_array($value)?'':mysql_real_escape_string($value)).'\'';}$i++;}$query.=')';
			if($this->query($query)){return mysql_insert_id($this->id);}}}
	function update($table, $values, $conditions){$this->connect();
		$query='update `'.$table.'` set ';
		$i=0;
		if($values){foreach($values as $key=>$value){if($key===0 or is_numeric($key)){$key=$value;
					$value=request($value);}if($i<>0){$query.=',';}if($key){if($value==='NULL'){$query.='`'.$key.'`=NULL';}else{$query.='`'.$key.'`=\''.mysql_real_escape_string($value).'\'';}$i++;}}if($condition_string = $this->condition_string($conditions)){$query.=' where '.$condition_string;}if($this->query($query)){return true;}}}
	function delete($table, $conditions){$this->connect();
		$this->query('DELETE FROM `'.$table.'` WHERE '.$this->condition_string($conditions));}static function convert_conditions($operator, $factors){switch ($operator){case 'COLUMN':
				if(is_array($factors[0])){print_r($factors[0]);
					echo '<pre>';
					debug_print_backtrace();
					exit();}return ' `'.addslashes($factors[0]).'` ';
				break;
			case 'FULLTEXT':
				return 'MATCH ('.$factors[0].') AGAINST ('.$factors[1].' IN BOOLEAN MODE)';
				break;
			case 'LIKE':
				return '('.$factors[0].' LIKE "%'.substr($factors[1],2,strlen($factors[1])-4).'%")';
				break;
			case 'NLIKE':
				return '('.$factors[0].' NOT LIKE "%'.substr($factors[1],2,strlen($factors[1])-4).'%")';
				break;
			case 'BW':
				return '('.$factors[0].' LIKE "'.substr($factors[1],2,strlen($factors[1])-4).'%")';
				break;
			case 'EW':
				return '('.$factors[0].' LIKE "%'.substr($factors[1],2,strlen($factors[1])-4).'")';
				break;
			case 'INT':
				$factors[0] = intval($factors[0]);
				return ' "'.mysql_escape_string($factors[0]).'" ';
				break;
			case 'REAL':
				$factors[0] = floatval($factors[0]);
				return ' "'.mysql_escape_string($factors[0]).'" ';
				break;
			case 'STRING':
				return ' "'.mysql_escape_string($factors[0]).'" ';
				break;
			case 'ID':
				return '(`id` = '.$factors[0].')';
				break;
			case '!':
				return ' NOT '.$factors[0].' ';
				break;
			case '!=':
				return '('.$factors[0].' <> '.$factors[1].')';
				break;
			case 'NOT_NULL':
				return '('.$factors[0].' is not null)';
				break;
			case 'NULL':
				return '('.$factors[0].' is null)';
				break;
			case 'IN':
				$sub_factors = array();
				for($i = 1; $i< sizeof($factors); $i++){$sub_factors[] = '( '.$factors[0].' = '.$factors[$i].' )';}return '( '.join(' OR ', $sub_factors).' )';
				break;
			default:
				return '( '.join(' '.$operator.' ', $factors).' )';
				break;}}function condition_string($conditions){if(is_string($conditions) or is_numeric($conditions)){$conditions = EId($conditions);}else{$conditions = CExpression::pre_process_conditions($conditions);}if($conditions){return $conditions->parse('CMySQLStore::convert_conditions');}return false;}function select_all($table, $conditions = false, $options = array()){$items = array();
		if(!isset($options['items_per_page'])){$options['items_per_page'] = 1000;}if($item = $this->select($table, $conditions, $options)){do{if(isset($item['id'])){$items[$item['id']] = $item;}else{$items[] = $item;}}while($item = $this->fetch());}return $items;}}?><?php

class CStore{static $default = false;public $relationships = array();public $items = array();public $connected = false;function __construct($items = ''){if(!$items){$this->items = array();}elseif(is_array($items)){$this->items = $items;}elseif(is_string($items)){eval('$this->items='.$items.';');}$this->connect();}function load_schema($file_name){$this->relationships = CList(CXml($file_name)->decode())->extract_id('name');}function connect(){$this->connected = true;}function close(){$this->connected = false;}function count($table, $conditions=false){return is_array($this->items)?sizeof($this->items):0;}function select($table, $conditions = false, $options = array()){$result = CList($this->items)->filter($conditions);if($result){return reset($result);}return array();}function select_all($table, $conditions = false, $options = array()){return CList($this->items)->filter($conditions);}function fetch($query_string = false){}function insert($table, $values){if(isset($values['id'])){$this->items[$values['id']] = $values;}else{$this->items[] = $values;}}function update($table, $values, $condition){$items = $this->select_all($table, $condition);foreach($items as $id=>$item){if(isset($values['id']) and $values['id']!=$id){$this->items[$values['id']] = $this->items[$id];unset($this->items[$id]);$id = $values['id'];}foreach($values as $key=>$value){$this->items[$id][$key] = $value;}}}function delete($table, $conditions){foreach($this->items as $id=>&$item){if(is_array($conditions)){if(CRecord($item)->test($conditions)){unset($this->items[$id]);}}elseif(!$conditions){unset($this->items[$id]);}elseif(is_array($item)){if(isset($item['id']) and $item['id'] == $conditions){unset($this->items[$id]);}}elseif($item == $conditions){unset($this->items[$id]);}}}function to_string(){return var_export($this->items,1);}function condition_string($condition){}function cascade_update($table, $old_id, $new_id){if(isset($this->relationships[$table])){foreach($this->relationships[$table]['relationships'] as $relationship){foreach($relationship['fields'] as $field){$this->update($relationship['table-name'], array($field=>$new_id),array($field=>$old_id));}}}}function cascade_delete($table, $id){if(isset($this->relationships[$table])){foreach($this->relationships[$table]['relationships'] as $relationship){foreach($relationship['fields'] as $field){$items = CTable($relationship['table-name'])->select_all(EEqual($field,EInt($id)));$this->delete($relationship['table-name'], array($field=>$id));foreach($items as $item){$this->cascade_delete($relationship['table-name'], $item['id']);}}}}}}function CStore($items = ''){return new CStore($items);}?><?php

class CTable{public $store;
	public $table;
	public $record;
	public $original_record;
	public $inserted_id;
	public $options = array();
	public $condition = false;
	function __construct($table, $record = false){if(is_object($table)){$this->store = $table;}else{$this->table = $table;
			$this->store = &CStore::$default;
			$this->record = $this->original_record = 
				is_object($record)?
					$record:(
						is_array($record)?
							CRecord($record):(
								$record?
									CRecord($this->store->select($table,EId($record))):false));}}function options($options = array()){return array_merge(is_array($options)?$options:array(), is_array($this->options)?$this->options:array());}function &condition($condition = array()){$this->condition = $condition;
		return $this;}function get_condition($condition = array()){if($this->condition){if($condition){$condition =  EAnd($this->condition, $condition);}else{$condition =  $this->condition;}}$this->condition = false;
		return $condition;}function &order_by($order_by){$this->options['order_by'] = $order_by;
		return $this;}function &items_per_page($items_per_page){$this->options['items_per_page'] = $items_per_page;
		return $this;}function &fields($fields){$this->options['fields'] = $fields;
		return $this;}function &page_no($page_no){$this->options['page_no'] = $page_no;
		return $this;}
	function &change_store(&$store){$this->store = &$store;
		return $this;}function count($condition){return $this->store->count($this->table, $this->get_condition($condition));}function math_fn($math_fn, $fieldname, $conditions = false){return $this->store->math_fn($math_fn, $fieldname, $this->table, $this->get_condition($conditions));}function sum($fieldname, $conditions = false){return $this->store->sum($fieldname, $this->table, $this->get_condition($conditions));}
	function select($condition = false, $options = array()){if(!$this->record){$this->record = CRecord();}if(!$this->original_record){$this->original_record = CRecord();}$this->record->data 
			= $this->original_record->data 
			= $this->store->select($this->table, $this->get_condition($condition), $this->options($options));
		return $this->record->data;}function select_all($conditions = false, $options = array()){return $this->store->select_all($this->table, $this->get_condition($conditions), $this->options($options));}function &update($values, $conditions = false){$this->store->update($this->table, $values, $this->get_condition($conditions));
		return $this;}function insert($values){return ($this->inserted_id = $this->store->insert($this->table, $values));}function &save($data = false){if($data){$this->record = new CRecord($data);}if($this->original_record and $this->original_record->data){$this->store->update($this->table, 
				$this->record->data, $this->original_record->id);
			if(isset($this->store->relationships[$this->table]) and ($this->original_record->id != $this->record->id)){$this->store->cascade_update($this->table, $this->original_record->id, $this->record->id);}}else
		if($this->record and $this->record->data){$this->inserted_id= $this->store->insert($this->table, $this->record->data);}return $this;}function &delete($id = false){if($id){$this->store->delete($this->table, $id);}else			
			if($this->original_record){$this->store->delete($this->table, $this->original_record->id);
					$id = $this->original_record->id;}if(isset($this->store->relationships[$this->table])){$this->store->cascade_delete($this->table, $id);}return $this;}function delete_all($condition = false){$this->store->delete($this->table, $this->get_condition($condition));}}
function CTable($table, $record = false){return new CTable($table, $record);}?><?php

class CXml{public $doc;
	function __construct($root = false, $data = false){$this->doc = new DOMDocument('1.0', 'utf-8');$this->doc->preserveWhiteSpace = false;$this->doc->formatOutput = true;if($root){if(preg_match('/[^\w]/',$root)){if(preg_match('/[\<\>]/',$root)){$this->doc->loadXML($root);}else{$this->load($root);}}else{$element = $this->doc->createElement($root);$this->doc->appendChild($element);}}}
	function &load($file_name){if(CFile::exists($file_name)){$this->doc->load($file_name);}return $this;}
	function &save($file_name){if(strpos($file_name, 'ftp://') !== false){CFile::ftp_fput(str_replace(FTP_PREFIX,'',$file_name), $this->doc->saveXML());}else{$this->doc->save($file_name);}return $this;}
	function code(){return $this->doc->saveXML();}
	function &encode($data, $node = false){if(!$node){$node = $this->doc->documentElement;}foreach($data as $key => $value){if(is_array($value)){if(is_int($key)){if($node->nodeName[strlen($node->nodeName)-1] == 's'){$key = substr($node->nodeName, 0, strlen($node->nodeName)-1);}else{$key = $node->nodeName;}}$this->encode($value, $node->appendChild($this->doc->createElement($key)));}else{if(strlen($value)>255 or preg_match('/[^a-zA-Z0-9\s-@\._]/',$value)){$elem = $this->doc->createElement($key);$elem->appendChild($this->doc->createCDATASection($value));$node->appendChild($elem);}else{$node->appendChild($this->doc->createElement($key, $value));}}}return $node;}
	function create_element($name, $values){if(is_string($values)){return $this->doc->createElement($name, $values);}else{$node = $this->doc->createElement($name);$this->encode($values, $node);return $node;}}
	function decode($node = false){if(!$node){$node = $this->doc->documentElement;}if(!$node){return array();}if($node->nodeType == XML_ELEMENT_NODE){$child_nodes = $node->childNodes;if($child_nodes->length == 1 and ($child_nodes->item(0)->nodeType == XML_TEXT_NODE or $child_nodes->item(0)->nodeType == XML_CDATA_SECTION_NODE)){$value = $child_nodes->item(0)->nodeValue;/*if(intval($value) >=1 and intval($value)==$value){return intval($value);}else */{if($value == "true"){return true;}else{if($value == "false"){return false;}else{return $value;}}}}elseif($child_nodes->length == 0){return '';}else{$results = array();if($child_nodes->length>1 and $child_nodes->item(0)->nodeName == $child_nodes->item(1)->nodeName){for ($i = 0; $i < $child_nodes->length; $i++){$results[$i] = $this->decode($child_nodes->item($i));}}else{for ($i = 0; $i < $child_nodes->length; $i++){$results[$child_nodes->item($i)->nodeName] = $this->decode($child_nodes->item($i));}}return $results;}}}
	function array2XML($arr = array(),$filename){$doc = new DOMDocument('1.0','utf-8');$doc->formatOutput = true;if(!empty($arr)){foreach($arr as $key=>$value ){$this->createNodes($doc,$key,$value);}$doc->save($filename);}else{return ;}}
	static function array2xmlstring($a, $level = 0, $suggest_name = ''){if(is_array($a)){$st = '';foreach($a as $key=>$value){$next_suggest_name = '';if(is_int($key)){$key = $suggest_name;}else{if($key[strlen($key)-1] == 's'){$next_suggest_name = substr($key, 0, strlen($key)-1);}}$st .= '
'.($level?str_repeat('	', $level):'').'<'.$key.'>'.CXml::array2XMLstring($value, $level+1, $next_suggest_name).((is_array($value) and $level)?str_repeat('	', $level):'').'</'.$key.'>
';}return $st;}else{return $a;}}
	static function xmlstring2array($xml_string){$xml = CXml();$xml->doc->loadXML($xml_string);return $xml->decode();}}function CXml($root = false){return new CXml($root);}?><?php

class CXmlStore extends CStore{
	public $xml;
	public $file_name;
	public $root;
	public $xpath;
	public $loaded = false;
	
	function __construct($file_name, $root_query = ''){$this->file_name = $file_name;
		$this->root = $root_query;
		parent::__construct();}
	function connect(){$this->xml = new CXml();}
	function save(){if($this->file_name){$this->xml->save($this->file_name);}}function load(){if(!$this->loaded and $this->file_name){$this->xml->load($this->file_name);
			$this->loaded = true;}}function count($table, $conditions = false){$this->load();
		return sizeof($this->select_all($table, $conditions));}
	function select($table, $conditions = false, $options = array()){$this->load();
		$xpath = new DOMXPath($this->xml->doc);
		if($items = $xpath->query($this->root.$table.$this->condition_string($conditions))){if($items->length > 0){return $this->xml->decode($items->item(0));}}return false;}function select_parent($table, $conditions = false){$this->load();
		$xpath = new DOMXPath($this->xml->doc);
		if($items = $xpath->query($this->root.$table.$this->condition_string($conditions))){if($items->length == 1){return $this->xml->decode($items->item(0)->parentNode->parentNode);}}return false;}
	function select_all($table, $conditions = false, $options = array()){$this->load();
		if($table === false){return $this->xml->decode();}else{$options = array_merge(array(
				'page_no' => 1, 
				'items_per_page' => 100
			),$options);
			$xpath = new DOMXPath($this->xml->doc);
			$query_string = $this->root.$table.$this->condition_string($conditions);
			if(!empty($conditions)){$query_string = rtrim($query_string,']').' and position()>'.($options['page_no']-1)*$options['items_per_page'].' and position()<='.$options['page_no']*$options['items_per_page'].']';}else{$query_string =$query_string.'[position()>'.($options['page_no']-1)*$options['items_per_page'].' and position()<='.$options['page_no']*$options['items_per_page'].']';}if($nodes = $xpath->query($query_string)){$items = array();
				foreach($nodes as $node){$item = $this->xml->decode($node);
					if(is_array($item) and isset($item['id'])){$items[$item['id']] = $item;}else{$items[] = $item;}}if(isset($options['order_by'])){return CList($items)->order($options['order_by'])->items;}return $items;}}return false;}
	function insert_list($table, $values){if($values){foreach($values as $value){$this->insert($table, $value, false);}$this->save();}}function insert($table, $values, $save = true){$this->load();
		$xpath = new DOMXPath($this->xml->doc);
		if($nodes = $xpath->query($this->root.$table) and $nodes->length > 0){$table_name = explode('/', $table);
			$nodes->item(0)->parentNode->appendChild($this->xml->create_element($table_name[count(($table_name))-1], $values));
			if($save){$this->save();}return true;}else{$arr_table = explode('/',$table);
			$last_tag = $arr_table[count($arr_table)-1];
			$first_tag = $arr_table[count($arr_table)-2];
			array_pop($arr_table);
			if($node = $xpath->query($this->root.implode('/',$arr_table)) and $node->length > 0){$data = array($last_tag=>$values);
				$this->xml->encode($data, $node->item(0));
				if($save){$this->save();}}else{array_pop($arr_table);
				$path_way = implode('/',$arr_table);
				$data = array($first_tag=>array($last_tag=>$values));
				$parent_path = $this->root.$path_way;
				if($parent_path{strlen($parent_path)-1}== '/'){$parent_path = substr($parent_path, 0, strlen($parent_path)-1);}if($node = $xpath->query($parent_path) and $node->length > 0){$this->xml->encode($data, $node->item(0));
					if($save){$this->save();}}else{return false;}}}}
	function update($table, $values, $condition){$this->load();
		$xpath = new DOMXPath($this->xml->doc);
		if($nodes = $xpath->query($this->root.$table.$this->condition_string($condition)) and $nodes->length > 0){$has_changed = false;
			foreach($nodes as $node){if($node->parentNode){$old_values = $this->xml->decode($node);
					$change = false;
					foreach($values as $name => $value){if(!isset($old_values[$name]) or $old_values[$name] != $value){$change = true;}$old_values[$name] = $value;}if($change){$has_changed = true;
						$table_name = explode('/', $table);
						$node->parentNode->replaceChild($this->xml->create_element($table_name[count(($table_name))-1],$old_values), $node);}}}if($has_changed){$this->save();}}}
	function delete($table, $condition){$this->load();
		$xpath = new DOMXPath($this->xml->doc);
		if($nodes = $xpath->query($this->root.$table.$this->condition_string($condition)) and $nodes->length > 0){foreach($nodes as $node){$node->parentNode->removeChild($node);}}$this->save();}
	function select_all_order($table, $conditions = false, $field){$this->load();
		$xpath = new DOMXPath($this->xml->doc);
		if($nodes = $xpath->query($this->root.$table.$this->condition_string($conditions))){$items = array();
			foreach($nodes as $node){$items[] = $this->xml->decode($node);}$array_sort = array();
			foreach ($items as $value){$array_sort[] = $value[$field];}array_multisort($array_sort,$items);
			return $items;}return false;}
	function count_result($table, $conditions = false, $options = array()){$result = $this->select_all($table, $conditions, $options);
		if($result){return count($result);}else{return 0;}}static function convert_conditions($operator, $factors){switch ($operator){case 'COLUMN':
				return './'.addslashes($factors[0]);
				break;
			case 'FUNCTION':
				$params = $factors;
				unset($params[0]);
				return addslashes($factors[0]).'('.join(',', $params).')';
				break;
			case 'STRING':
			case 'INT':
			case 'REAL':
				return '\''.addslashes($factors[0]).'\'';
				break;
			case 'ID':
				return '(./id = '.$factors[0].')';
				break;
			case '!':
				return ' not ('.$factors[0].')';
				break;
			case 'IN':
				$sub_factors = array();
				for($i = 1; $i< sizeof($factors); $i++){$sub_factors[] = '('.$factors[0].' = '.$factors[$i].' )';}return join(' or ', $sub_factors);
				break;
			default:
				if(sizeof($factors) == 1){return strtolower($operator).'('.$factors[0].')';}else{return '('.join(strtolower($operator), $factors).')';}break;}}function condition_string($conditions){if(is_string($conditions) or is_numeric($conditions)){$conditions = EId($conditions);}else{$conditions = CExpression::pre_process_conditions($conditions);}if($conditions){return '['.$conditions->parse('CXmlStore::convert_conditions').']';}return false;}}
function CXmlStore($file_name, $root_query = ''){return new CXmlStore($file_name, $root_query);}?><?php 

class CForm{public $layout_file_name;
	function __construct($layout_file_name){$this->layout_file_name = $layout_file_name;}function &prepare_edit($data){if(is_array($data)){foreach($data as $key=>$value){if(!isset($_POST[$key])){$_POST[$key] = $value;}}}elseif($data and request('cmd')=='edit'){$this->prepare_edit(CTable($data)->select(EId(request('id'))));}return $this;}function &render_custom_data(&$data, &$fields, &$input_types){foreach($fields as $field){if(isset($input_types[$field['type']]) and isset($input_types[$field['type']]['select-code']) and isset($data[$field['name']])){$value = $data[$field['name']];
				eval($input_types[$field['type']]['select-code']);
				$data[$field['name']] = $value;}}return $this;}function &get_custom_data_source($data_source){return $this;}function &parse($params = array(), $extra = ''){$params['root_url'] = CPortal::$root_url;
		$params['static_url'] = CPortal::$static_url;
		$cache_name = $this->layout_file_name;
		if(DEBUG or !($cache = CSystem::$cache->get($cache_name))){$cache = CFormLayout(file_get_contents($this->layout_file_name))->parse().$extra;
			$code = 'SYS.using ('.CString(array('name'=>'<?php echo module()->name;?>', 'id'=>'<?php echo module()->id;?>', 'parent_id'=>'<?php echo module()->parent_id;?>'))->json();
			$cache = str_replace(array('SYS.moduleReady(', 'SYS.using()','SYS.using(',),array(
				'SYS.moduleReady(<?php echo module()->id;?>,' ,$code.')',$code.','), $cache);
			CSystem::$cache->set($cache_name, $cache);}if(!request('module')){portal()->script .= output()->get(eval(' ?>'.CForm::strip_script($cache).'<?php '));}eval(' ?>'.$cache.'<?php ');
		return $this;}static function strip_script(&$cache){$code = '';
		$script = '';
		$offset = 0;
		while(($pos1 = strpos($cache, '<script', $offset))!==false){if($pos2 = strpos($cache, '>', $pos1)){while($pos2 and $cache{$pos2-1}== '?'){$pos2 = strpos($cache, '>', $pos2+1);}if ($pos2 and $pos3 = strpos($cache, '</script>', $pos2)){$pos3 += strlen('</script>');
					$code .= substr($cache, $offset, $pos1-$offset);
					if(strpos(substr($cache, $pos1, $pos2-$pos1),'src')){$script .= '
	</script>
	'.substr($cache, $pos1, $pos3-$pos1).'
	<script type="text/javascript">
	';}else{$script .= substr($cache, $pos2+1, $pos3-strlen('</script>')-$pos2-1);}$offset = $pos3;}else 
					break;}else 
				break;}$code .= substr($cache, $offset);
		$cache = $code;
		return $script;}}function CForm($layout_file_name){return new CForm($layout_file_name);}function image($url){if(strpos($url, 'http://')){return $url;}if(strpos($url, '/upload/') === 0){return FILE_SERVER_URL.$url;}if(strpos($url, 'upload/') === 0){return FILE_SERVER_URL.'/'.$url;}if(!$url){return CPortal::$root_url.portal()->skin().'images/no-image.jpg';}return $url;}?><?php 

class CFormLayout{public $code;
	public $tokens;
	public $error = false;
	public $line = 0;
	public $start_loop_index = 0;
	public $loop_index = 0;
	public $loops = array();
	public $file_input_types = array();
	static $layout_tags = array(
		'BEGIN_LIST' => '<\!\-\-LIST\(',
		'BEGIN_FOR' => '<\!\-\-FOR\(',
		'BEGIN_IF' => '<\!\-\-IF\(',
		'CLOSE_TAG' => '\)\-\->',
		'BEGIN_SWITCH' => '<\!\-\-SWITCH\(',
		'END_LIST' => '<\!\-\-\/LIST\-\->',
		'END_IF' => '<\!\-\-\/IF\-\->',
		'END_FOR' => '<\!\-\-\/FOR\-\->',
		'END_SWITCH' => '<\!\-\-\/SWITCH\-\->',
		'BEGIN_INPUT' => '\<i\:([\w\-]+)\s*([^>]*)\>',
		'END_INPUT' => '<\/i:([\w\-]+)\s*>',
		'ELSE' => '<!--ELSE-->',
		'DEFAULT' => '<!--DEFAULT-->',
		'CASE' => '<\!\-\-CASE\(',
		'LEFT_BRACKET' => '\\\{',
		'RIGHT_BRACKET' => '\\\}',
		'EVAL_VARIABLE' => '\{\{([^\}\r\n]+)\}\}',
		'VARIABLE' => '\{([^\}\r\n]+)\}',
		'BEGIN_PHP' => '\<\?php',
		'END_PHP' => '\?\>',
		'NEW_LINE' => "\r\n",
	);
	static $layout_template_tags = array(
		'METHOD_CALL' => '\-\>([\w]+)\(',
		'ARRAY' => '\[([\w]+)\]',
		'CLASS_ATTRIBUTE' => '\-\>([\w]+)',
		'FUNCTION_CALL' => '([\w\:\$]+)\(',
		'CUSTOM_FIELD' => '\%\%',
		'RIGHT_PARENTHESE' => '\)',
		'RIGHT_BRACE' => '\]',
		'STRING' => '\'([^\']+)\'',
		'PHP_VARIABLE' => '(\$[\w]+)',
		'CLASS_STATIC' => '([\w]+)\:\:',
		'VARIABLE' => '([\w\.\-]+)',
	);
	static $params_template_tags = array(
		'SLASH_QUOTE' => '\\\\"',
		'QUOTE' => '"',
		'EQUAL' => '=',
	);
	static $input_types = array();
	function __construct($code, $start_loop_index = 1, $loops = array()){$this->start_loop_index = $start_loop_index;
		$this->code = $code;
		$this->loops = $loops;}static function input_types($file_input_types = 'lib/form/input-types.xml'){if(!isset(CFormLayout::$file_input_types[$file_input_types])){CFormLayout::$file_input_types[$file_input_types] = 1;
			CFormLayout::$input_types = CFormLayout::$input_types + CList(CXml(CFormLayout(file_get_contents($file_input_types))->parse())->decode())->extract_id('name');}}function parse(){require_once 'lib/utils/CTranslation.php';
		require_once 'lib/utils/CToken.php';
		$this->tokens = CTranslation($this->code, CFormLayout::$layout_tags)->tokenize();
		$pos = 0;
		$this->line = 0;
		$this->loop_index = $this->start_loop_index;
		try{$result = $this->translate($pos);
			if(module()){$result = str_replace('</form','<input type="hidden" name="submit_form_id" value="'.module()->id.'"><input type="hidden" name="module_id" value="'.module()->id.'"></form', $result);}}catch(Exception $e){echo 'Parse error, stop parsing, return false.'.$e->getMessage();
			Clog('SYSTEM','Parse error, stop parsing, return false.');
			$result = '';}if(DEBUG){}return $result;}function translate(&$pos, $in_php = false){$code = '';
		$last_in_php = $in_php;
		$end_token = false;
		$in_code_php = false;
		while(!$end_token and $pos < sizeof($this->tokens)){$token = CToken($this->tokens[$pos]);
			switch($token->type){case 'TEXT':
				if($in_php){if(trim($token->param)){if(!$in_code_php){$code .= '?>';
							$in_php = false;}$code .= $token->param;}}else{$code .= $token->param;}break;
			case 'BEGIN_PHP':
				$code .= '<?php ';
				$in_code_php = true;
				$in_php = true;
				break;
			case 'END_PHP':
				$code .= ' ?>';
				$in_php = false;
				$in_code_php = false;
				break;
			case 'BEGIN_LIST':
				$pos++;
				if(CToken($this->tokens[$pos])->type != 'TEXT'){throw new Exception('expression expected!');}if(CToken($this->tokens[$pos+1])->type != 'CLOSE_TAG'){throw new Exception(')--> expected!');}$this->loops[CToken($this->tokens[$pos])->param] = $this->loop_index;
				$for_var = $this->translate_variable(CToken($this->tokens[$pos])->param);
				$code .= ($in_php?'':'<?php').' $index'.$this->loop_index.' = 0;
'.((!strpos($for_var,'('))?'if(isset('.$for_var.'))':'').'
foreach('.$for_var.' as '.((!strpos($for_var,'('))?'&':'').'$item'.$this->loop_index.'){$index'.$this->loop_index.'++;
';
				$pos++;
				$this->loop_index ++;
				$code .= $this->translate($pos, true);
				$code .= '}'.($in_php?'':'?>');
				if(CToken($this->tokens[$pos])->type != 'END_LIST'){throw new Exception('<!--/LIST--> expected!');
					$pos++;
					return $code;}break;
			case 'BEGIN_FOR':
				$pos++;
				if(CToken($this->tokens[$pos])->type != 'TEXT'){throw new Exception('expression expected!');}if(CToken($this->tokens[$pos+1])->type != 'CLOSE_TAG'){throw new Exception(')--> expected!');}$code .= ($in_php?'':'<?php').' 
for('.$this->translate_variable(CToken($this->tokens[$pos])->param).'){';
				$pos++;
				$code .= $this->translate($pos, true);
				$code .= '}'.($in_php?'':'?>');
				if(CToken($this->tokens[$pos])->type != 'END_FOR'){throw new Exception('<!--/FOR--> expected!');
					$pos++;
					return $code;}break;
			case 'BEGIN_SWITCH':
				$pos++;
				if(CToken($this->tokens[$pos])->type != 'TEXT'){throw new Exception('expression expected!');}if(CToken($this->tokens[$pos+1])->type != 'CLOSE_TAG'){throw new Exception(')--> expected!');}$code .= ($in_php?'':'<?php').' 
switch('.$this->translate_variable(CToken($this->tokens[$pos])->param).'){case time():
';
				$pos++;
				$code .= $this->translate($pos, true);
				$code .= '}'.($in_php?'':'?>');
				if(CToken($this->tokens[$pos])->type != 'END_SWITCH'){throw new Exception('<!--/SWITCH--> expected!');
					$pos++;
					return $code;}break;
			case 'NEW_LINE':
				$this->line++;
				$code .= "\n\r";
				break;
			case 'ELSE':
				$code .= ($in_php?'':'<?php').' }else{ '.($in_php?'':'?>');
				break;
			case 'DEFAULT':
				$code .= ($in_php?'':'<?php').' break; default:'.($in_php?'':'?>');
				break;
			case 'CASE':
				$pos++;
				if(CToken($this->tokens[$pos])->type != 'TEXT'){throw new Exception('expression expected!');}if(CToken($this->tokens[$pos+1])->type != 'CLOSE_TAG'){throw new Exception(')--> expected!');}$code .= ($in_php?'':'<?php').' break; ';
				$vars = explode('|', CToken($this->tokens[$pos])->param);
				foreach($vars as $var){$code .= 'case '.$var.':';}$code .= ($in_php?'':'?>');
				$pos ++;
				break;
			case 'END_LIST':
			case 'END_IF':
			case 'END_FOR':
			case 'END_SWITCH':
			case 'END_INPUT':
				$end_token = true;
				break;
			case 'BEGIN_IF':
				$pos++;
				if(CToken($this->tokens[$pos])->type != 'TEXT'){throw new Exception('expression expected!');}if(CToken($this->tokens[$pos+1])->type != 'CLOSE_TAG'){throw new Exception(')--> expected!');}$code .= ($in_php?'':'<?php').' if('.$this->translate_variable(CToken($this->tokens[$pos])->param).'){';
				$pos ++;
				$code .= $this->translate($pos, true);
				$code .= '}'.($in_php?'':'?>');
				if(CToken($this->tokens[$pos])->type != 'END_IF'){throw new Exception('<!--/IF--> expected!');
					$pos++;
					return $code;}break;
			case 'LEFT_BRACKET':
				$code.='{';
				break;
			case 'RIGHT_BRACKET':
				$code.='}';
				break;
			case 'BEGIN_INPUT':
				CFormLayout::input_types();
				$item_name = 'item'.($this->loop_index-1);
				$params = $this->get_params($token->params(1));
				$$item_name = array(
					'name' => '',
					'id' => '',
					'params' => $params
				);
				$item = &$$item_name;
				if(isset($params['name'])){$item['name'] = $params['name'];}if(isset($params['id'])){$item['id'] = $params['id'];}$pos++;
				$this->loop_index++;
				$child_value = $this->translate($pos, false);
				$item['value'] = $child_value?1:0;
				if(CToken($this->tokens[$pos])->type != 'END_INPUT' or CToken($this->tokens[$pos])->params(0) != $token->params(0)){throw new Exception('</i:'.$token->params(0).'> expected!');
					$pos++;
					return $code;}if(isset(CFormLayout::$input_types[strtoupper($token->params(0))])){$code .= ($in_php?'':'<?php ');
					$input = &CFormLayout::$input_types[strtoupper($token->params(0))];
					if(isset($input['params'])){foreach($input['params'] as $key => $value){if(!isset($item['params'][$key])){$item['params'][$key] = $value;}}}$code .= '$'.$item_name.' = '.var_export($item, true).';';
					if(isset($input['links'])){foreach($input['links'] as $link){$code .= 'link("'.$link.'");';}}$code .= ' ?>'.str_replace('$item0', '$'.$item_name, str_replace('<?php echo $item0[\'value\'];?>', $child_value,$input['template'])).'<?php ';
					$code .= ($in_php?'':'?>');}$this->loop_index--;
				break;
			case 'END_INPUT':
				break;
			case 'EVAL_VARIABLE':
				$code .= ($in_php?'':'<?php').' eval(\' ?>\'.CFormLayout('.$this->translate_variable($token->param).','.($this->loop_index).','.var_export($this->loops,1).')->parse().\'<?php \');'.($in_php?'':'?>');
				break;
			case 'VARIABLE':
				$code .= ($in_php?'':'<?php').' echo '.$this->translate_variable($token->param).';'.($in_php?'':'?>');
				break;}if(!$end_token){$pos++;}}if($in_php != $last_in_php){if($last_in_php){$code .= '<?php ';}else{$code .= '?>';}}return $code;}function get_params($text){$params = array();
		$current_param = '';
		$state = 0;
		$tokens = CTranslation($text, CFormLayout::$params_template_tags)->tokenize();
		$custom_field = false;
		$i = 0;
		foreach($tokens as $token){$token = CToken($token);
			$ok = false;
			switch($token->type){case 'TEXT':
					if($state == 3){$params[$current_param] .= $token->param;
						$ok = true;}elseif(trim($token->param)){if($state == 0){$current_param = trim($token->param);
							$params[$current_param] = '';
							$state ++;
							$ok = true;}}break;
				case 'QUOTE':
					if($state == 2){$state ++;
						$ok = true;}elseif($state == 3){$state = 0;
						$ok = true;}break;
				case 'SLASH_QUOTE':
					if($state == 3){$params[$current_param] .= '"';
						$ok = true;}break;
				case 'EQUAL':
					if($state == 1){$state = 2;
						$ok = true;}elseif($state == 3){$params[$current_param] .= '=';
						$ok = true;}break;}if(!$ok){if($state == 1){throw new Exception('= expected!');}elseif($state == 2){throw new Exception('" expected!');}elseif($state == 0){throw new Exception('identify expected!');}}}return $params;}function translate_variable($var){$code = '';
		if(preg_match('/[^\w\.\-\#\[\]]/',$var) or strpos($var, '.[')){$tokens = CTranslation(str_replace('.[','%%',$var), CFormLayout::$layout_template_tags)->tokenize();
			$custom_field = false;
			$i = 0;
			foreach($tokens as $token){$token = CToken($token);
				switch($token->type){case 'TEXT':
						$code .= $token->param;
						break;
					case 'ARRAY':
						$code .= '[\''.$token->param.'\']';
						break;
					case 'STRING':
						if(sizeof($tokens)==1){$code .= 'language(\''.$token->param.'\')';}else{$code .= '\''.$token->param.'\'';}break;
					case 'CUSTOM_FIELD':
						$custom_field = true;
						break;
					case 'METHOD_CALL':
						$code .= '->'.$token->param.'(';
						break;
					case 'CLASS_ATTRIBUTE':
						$code .= '->'.$token->param;
						break;
					case 'FUNCTION_CALL':
						$code .= $token->param.'(';
						break;
					case 'RIGHT_BRACE':
						if($custom_field){$code .= ']';}break;
					case 'RIGHT_PARENTHESE':
						$code .= ')';
						break;
					case 'PHP_VARIABLE':
						$code .= $token->param;
						break;
					case 'CLASS_STATIC':
						$code .= $token->param.'::';
						break;
					case 'VARIABLE':
						if($i<sizeof($tokens)-1 and CToken($tokens[$i+1])->type == 'CUSTOM_FIELD'){$code .= str_replace('\'temp\']','',$this->translate_variable($token->param.'.temp'));}else{$code .= $this->translate_variable($token->param);}break;}$i++;}}else
		if(is_numeric($var) or !preg_match('/[^A-Z\_\-]/',$var)){$code .= $var;}else{$vars = explode('.',$var);
			$index = array_pop($vars);
			if(strpos($index,'[')){if($index[strlen($index)-1] != ']'){$this->error('] expected!');}else{$index = explode('[',substr($index,0, strlen($index)-1));
					$index = '[\''.$index[0].'\'][\''.$index[1].'\']';}}else{$index = '[\''.$index.'\']';}if(!sizeof($vars)){$code = '$params'.$index.'';}else{if(join('.',$vars) == 'each'){if($index == '[\'_index\']'){$code = '$index'.($this->loop_index-1);}else{$code = '$item'.($this->loop_index-1).$index;}}elseif(isset($this->loops[join('.',$vars)])){if($index == '[\'_index\']'){$code = '$index'.$this->loops[join('.',$vars)];}else{$code = '$item'.$this->loops[join('.',$vars)].$index;}}else{if($index == '[\'_index\']'){$code = '$index'.($this->start_loop_index + sizeof($vars) - 2);}else{$code = '$item'.($this->start_loop_index + sizeof($vars) - 2).$index;}}}}return $code;}}function CFormLayout($code, $start_loop_index = 1, $loops = array()){return new CFormLayout($code, $start_loop_index, $loops);}function array2list($items){$new_items = array();
	foreach($items as $key=>$value){$new_items[] = array('id'=>$key, 'value'=>$value);}return $new_items;}?><?php

class CUrl{static $root = false;
	static $mode = 'rewrite';
	static function build_current($params=array(),$anchor=''){return CUrl::build(CURL::get('page','home'),$params,$anchor);}static function build($page,$params=array(),$anchor='', $url_mode = ''){if(CUrl::$mode == 'ajax' and ($url_mode == '' or $url_mode == 'ajax') and $page){$params['url_mode'] = 'ajax';
			$params['page'] = $page;
			return 'javascript:if(typeof(SYS)!=\'undefined\' && typeof(SYS.Page)!=\'undefined\')SYS.Page.load('.str_replace('"','\'',CString($params)->json()).');void(0);';}$root_url = CPortal::$root_url;
		switch($page){case 'product_list':
			if(isset($params['category_id'])){return $root_url.'danh-muc/'.$params['category_id'].'.html';}break;
		case 'quick_sale':
			if(isset($params['id']) and isset($params['sale_link_id'])){return $root_url.'ban-hang/'.$params['sale_link_id'].'/'.(isset($params['category_id'])?$params['category_id'].'/':'').$params['id'].'_'.(isset($params['name'])?preg_replace('/[^a-zA-Z0-9_-]/','-',$params['name']):'').'.html';}break;
		case 'product_detail':
			if(isset($params['id'])){return $root_url.'san-pham/'.(isset($params['category_id'])?$params['category_id'].'/':'').$params['id'].'_'.(isset($params['name'])?preg_replace('/[^a-zA-Z0-9_-]/','-',$params['name']):'').'.html';}break;
		// The Life ------------------------------------------------------

		case 'product_compare':
			if(isset($params['products'])){return $root_url.$params['products'].'/so-sanh.html';}break;
		// The Life ------------------------------------------------------			
		
		case 'personal_transaction_detail':
			if(isset($params['id'])){return $root_url.'don-hang/'.$params['id'].'.html';}break;
		case 'sign_in':
			if(!$params){return $root_url.'dang-nhap.html';}break;
		case 'cart':
		case 'shopping_cart':
			return $root_url.'gio-hang.html';
		case 'cart_checkout':
			return $root_url.'thanh-toan.html';
		case 'help':
			if(isset($params['id'])){return $root_url.'ho-tro/'.$params['id'].'.html';}break;
		case 'salesman_help':
			if(isset($params['id'])){return $root_url.'tu-van-vien/'.$params['id'].'_'.(isset($params['name'])?preg_replace('/[^a-zA-Z0-9_-]/','-',$params['name']):'').'.html';}break;
		case 'personal':
			return $root_url.'ca-nhan.html';
		case 'message':
			return $root_url.'tin-nhan.html';
		case 'provider':
			return $root_url.'nha-cung-cap.html';
		case 'salesman_profile':
			if(isset($params['id'])){return $root_url.'nguoi-ban/'.$params['id'].'.html';}break;
		case 'customer_profile':
			if(isset($params['id'])){return $root_url.'nguoi-mua/'.$params['id'].'.html';}break;}$request_string = $root_url.((!isset($params['module']) and $page)?'?page='.$page:'?');
		if(!isset($params['portal']) and portal()){$params['portal'] = portal()->id;}if($params['portal'] == CPortal::$default){unset($params['portal']);}if(request('_log') and user()->is_admin()){$params['_log'] = request('_log');}return $request_string.CUrl::make_url($params);}static function make_url($params){$request_string = '';
		if ($params){foreach ($params as $param=>$value){if(is_numeric($param)){if(request($value)){$request_string .= '&'.$value.'='.urlencode(request($value));}}else{$request_string .= '&'.$param.'='.urlencode($value);}}}return $request_string;}static function redirect_current($params=array(),$anchor = ''){CUrl::redirect(CURL::get('page','home'),$params,$anchor);}static function redirect_href($params=false){if(CUrl::check('href')){CUrl::redirect_url(CUrl::attach(request('href'),$params));
			  return true;}}static function redirect($page=false,$params=false, $anchor=''){if(!$page and !$params){CUrl::redirect_url();}else{CUrl::redirect_url(CUrl::build($page, $params,$anchor));}}static function redirect_url($url=false){if(!$url||$url==''){$url='?'.$_SERVER['QUERY_STRING'];}header('Location:'.str_replace('&amp;','&',$url));
		CSystem::end();}static function access_denied(){if(CURL::get('page','home')!='home'){CUrl::redirect('home');}else{CSystem::end();}}static function get_num($name,$default=''){if (preg_match('/[^0-9.,]/',CUrl::get($name))){return $default;}else{return str_replace(',','.',str_replace('.','',request($name)));}}static function get($name,$default=''){if (isset($_POST[$name])){return $_POST[$name];}else
			if(isset($_GET[$name])){return $_GET[$name];}else{return $default;}}static function sget($name,$default=''){return strtr(CUrl::get($name, $default),array('"'=>'\\"'));}static function jget($name,$default=''){return CString(CUrl::get($name, $default))->json();}}function url($page = false, $params=array(),$anchor='', $url_mode = ''){if(is_array($page)){if(request('module')){return CURL::build(false, $page+array('module'=>request('module')), is_string($params)?$params:'', $url_mode);}else{return CURL::build_current($page, is_string($params)?$params:'', '', $url_mode);}}elseif($page){return CURL::build($page, $params, $anchor, $url_mode);}else{return CPortal::$root_url.'?'.$_SERVER['QUERY_STRING'];}}function ajax_url($params=array(),$anchor=''){return url($params+array('module_id'=>module()->id), $anchor);}function request($name,$default = ''){return CUrl::get($name,$default);}function param($name){if(request($name)){return '&'.$name.'='.urlencode(request($name));}}function redirect($page = array(), $params=array(),$anchor=''){if(is_array($page)){CURL::redirect_current($page, is_string($params)?$params:'');}else{return CURL::redirect($page, $params, $anchor);}}?><?php
class CModule extends CRecord{static $global_id = 0;
	static $current;
	public $error_messages = array();
	function __construct($data){parent::__construct($data);
		$last = &CModule::$current;
		CModule::$current = &$this;
		$this->init();
		CModule::$current = &$last;}function extend_layout($name, $params, $module = false){if(CFile::exists($this->path.'/'.$name.'.tpl')){$layout = $this->path.'/'.$name.'.tpl';}else{$parents = class_parents($this);
			$layout = false;
			foreach($parents as $parent){if(CFile::exists($path = CModule::module_path($parent).'/'.$name.'.tpl')){$layout = $path;
					break;}}}if(!$layout){return;}CForm($layout)->parse($params);}function init(){}function submit(){if(request('cmd')){if(method_exists($this,'on_'.request('cmd'))){try{eval('$this->on_'.request('cmd').'();');}catch (Exception $e){$this->error('Error', $e->getMessage());}if(portal()->script){echo '<script type="text/javascript">'.portal()->script.'</script>';}CSystem::end();}}}function draw(){}function path(){return $this->path;}function error($input = false, $message = false){if($message){$this->error_messages[] = array('input'=>$input, 'message' => $message);}else{if($input){return CList($this->error_messages)->filter(array('input'=>$input));}else{return $this->error_messages;}}}function is_error(){return $this->error_messages != array();}function check($name, $options = array()){require_once 'lib/utils/CInput.php';
		try{CInput($name, $options)->check();}catch (Exception $e){$this->error('Error', $e->getMessage());}}function error_messages($layout = false){if(!$layout){$layout = 'lib/form/error_messages.tpl';}CForm($layout)->parse(array(
			'items' => $this->error_messages
		));}function input_error($input, $layout = false){if(!$layout){$layout = 'lib/portal/input_error.tpl';}CForm($layout)->parse(array(
			'items' => $this->error($input)
		));}static function load(){if(isset(CPortal::$components['MODULE.'.request('module')]) and $module = CPortal::$components['MODULE.'.request('module')]){CPage::$current = CPage(array('name'=>'run_by_module'));
			$module_name = $module['name'];
			CPage::$current->all_blocks = array(
				new $module_name(array_merge_recursive(
					CXml($module['path'].'/module.xml')->decode(),
					array(
						'path'=>$module['path'],
						'module' => request('module'),
						'region' => 'center',
						'position' => 1,
						'settings' => $_GET
					)
				))
			);
			CPage::$current->submit();
			CModule::$current = &CPage::$current->all_blocks[0];
			CPage::$current->all_blocks[0]->draw();}}function can_edit(){return user()->can_edit();}function can_add(){return user()->can_add();}function can_delete(){return user()->can_delete();}function can_view(){return user()->can_view();}function can_view_detail(){return user()->can_view_detail();}function can_moderator(){return user()->can_moderator();}function can_developer(){return user()->can_developer();}function can_admin(){return user()->can_admin();}function can_editor($category_id = -1, $content_type = 0){if($this->can_admin()){return true;}if($category_id == -1){$category_id = request('category_id');}return CTable('content_privilege')->select(array('user_id'=>user()->id, 'category_id'=>$category_id, 'portal_id'=>portal()->id, 'type'=>$content_type));}function frame($title, $content, $path = false){if(!$path){$path = module()->setting('layout',$this->path().'/default.tpl');}$params = array(
			'title' => $title,
			'layout_path' => substr($path,0,strrpos($path,'/')),
			'content' => $content
		);
		$layout = str_replace('{region(\'center\')}','{content}',file_get_contents($path));
		if(!request('module')){$script = CForm::strip_script($layout);}eval(' ?>'.CFormLayout($layout)->parse().'<?php ');
		if(!request('module')){portal()->script .= output()->get(eval(' ?>'.CFormLayout($script)->parse()));}}function get_frame($path = '', $type = ''){if(!$path){$path = module()->setting('layout',$this->path().'/default.tpl');}if(!$type){$type = module()->setting('type');}$layout = str_replace('{setting(\'type\')}','{type}',file_get_contents($path));{$script = CForm::strip_script($layout);}$pos = strpos($layout,'{region(\'center\')}');
		$params = array(
			'title' => '[[title]]',
			'layout_path' => substr($path,0,strrpos($path,'/')),
			'type' => $type
		);
		$begin = output()->get(@eval(' ?>'.CFormLayout(substr($layout,0,$pos))->parse()));
		$end = output()->get(@eval(' ?>'.CFormLayout(substr($layout,$pos + strlen('{region(\'center\')}')))->parse()));{portal()->script .= output()->get(eval(' ?>'.CFormLayout($script)->parse()));}return array('begin'=>$begin, 'end'=>$end);}function frame_title($frame_code, $title){return str_replace('[[title]]',$title,$frame_code);}static function module_path($class_name){if(isset(CPortal::$components['MODULE.'.$class_name]) and $module = CPortal::$components['MODULE.'.$class_name]){return $module['path'];}}function skin($st){return str_replace(array('{root_url}', '{static_url}'),array(CPortal::$root_url, CPortal::$static_url),$st);}}function CModule($id){return new CModule($id);}function error_messages($layout = false){try{return module()->error_messages($layout);}catch(Exception $e){}}function input_error($input, $layout = false){try{return module()->input_error($input, $layout);}catch(Exception $e){}}function error($input = false){try{return module()->error($input);}catch(Exception $e){}}function &module(){if(CModule::$current){return CModule::$current;}else{$block = new CModule(array('id'=>0));
		return $block;}}function jm(){return 'SYS.blocks['.module()->id.']';}function __autoload($class_name){if(strpos($class_name,'::')){$class_name = substr($class_name, strrpos($class_name,'::')+2);
		exit();}if($path = CModule::module_path($class_name)){require_once $path.'/class.php';}else
	if(file_exists('lib/utils/'.$class_name.'.php')){require_once 'lib/utils/'.$class_name.'.php';}}function setting($name, $default = NULL){return module()->setting($name, $default);}function module_path(){return module()->path();}?><?php
class CPage extends CRecord{static $current = false;
	static $drawing = false;
	static $edit_mode = false;
	static $default_page = 'home';
	public $all_blocks = array();
	public $params = array();
	static $max_module_id = 0;
	function __construct($data){parent::__construct($data);
		CPage::$max_module_id = intval(request('module_id'));
		$jsConfig = session('jsConfig');
		if(!$jsConfig){$jsConfig = '{}';}if(DEBUG){$modules = 'vhv_all_modules='.CPage::get_modules_js().';';
			if(!is_dir('publish/'.portal()->id)){mkdir('publish/'.portal()->id);}if(DEBUG and !CFile::exists('publish/'.portal()->id.'/modules.js') or file_get_contents('publish/'.portal()->id.'/modules.js') != $modules){file_put_contents('publish/'.portal()->id.'/modules.js', $modules);}}$this->params = array(
			'keywords' => portal()->setting('keywords'),
			'title' => portal()->setting('title'),
			'description' => portal()->setting('description'),
			'links' => '',
			'jsConfig'=>$jsConfig,
			'user_id'=>session('user_id')?session('user_id'):'guest',
			'is_admin'=>user()->is_admin()?'true':'false',
			'is_debug'=>DEBUG?'true':'false',
			'portal_id' => portal()->id,
			'root_url' => CPortal::$root_url,
			'static_url' => CPortal::$static_url
		);}function submit(){if(isset($_GET['submit_form_id']) or isset($_POST['submit_form_id']) or request('submit_form_id')){foreach($this->all_blocks as &$block){if(isset($block->id) and intval(request('submit_form_id')) == intval($block->id)){$last = &CModule::$current;
					CModule::$current = &$block;
					$block->submit();
					CModule::$current = &$last;}}}CPage::$drawing = true;}static function load($page = false){if(!$page or is_int($page)){if(request('module')){if(request('page') and is_int(request('page'))){$page = CPage::get_current_page(portal()->data);
					if($page['name'] == request('page')){$cache_name = 'CPage::pages::'.$page['name'].'.'.$page['params'].'.'.request('module');
						if(DEBUG or !($cache = CSystem::$cache->get($cache_name))){require_once ROOT_DIR.'lib/utils/CPageCache.php';
							$page_cache = new CPageCache($page, request('module'));
							$cache = $page_cache->cache($cache_name);}eval(' ?>'.$cache.'<?php ');
						echo '<script type="text/javascript">'.portal()->script.'</script>';
						return;}}else{$cache_name = 'CModule::modules::'.request('module');
					if(DEBUG or !($cache = CSystem::$cache->get($cache_name))){require_once ROOT_DIR.'lib/utils/CPageCache.php';
						$page_cache = new CPageCache('', request('module'));
						$cache = $page_cache->cache($cache_name);}eval(' ?>'.$cache.'<?php ');
					echo '<script type="text/javascript">'.portal()->script.'</script>';
					return;}return;}$page = CPage::get_current_page(portal()->data);}if($page){$cache_name = 'CPage::pages::'.$page['name'].'.'.$page['params'];
			if(DEBUG or !($cache = CSystem::$cache->get($cache_name))){require_once ROOT_DIR.'lib/utils/CPageCache.php';
				$page_cache = new CPageCache($page, false);
				$cache = $page_cache->cache($cache_name);}eval(' ?>'.$cache.'<?php ');
			if(defined('EXPORT_JS_AND_CSS') and  CPage::$current->name != 'run_by_module'){echo '
				<script type="text/javascript">
				$(function(){setTimeout(function(){SYS.makeLinksCache(\''.CPage::$current->name.'\');},5000);});
				</script>
				';}/*$content = ob_get_flush();
			print_r(CPage::get_links($content));*/}}/*static function get_links($content){$links = array();
		if(preg_match_all('/SYS\.load\(([\s\na-zA-Z0-9\.\_\-\/]+)\)/', $content, $patterns)){foreach($patterns[1] as $link){$links[] = $link;}}return $links;}*/
	static function get_current_page($portal_data, $page_name = false, $use_default_portal = false){if(!$page_name){$page_name = request('page', CPage::$default_page);}if(!($pages = CList(CList(CPortal::$components)->filter(array('type'=>'PAGE', 'name'=>$page_name)))->order('params desc')->items)){$pages =  CList(CList(CPortal::$components)->filter(array('type'=>'PAGE', 'name'=>CPage::$default_page)))->order('params desc')->items;}if(isset($portal_data['name'])){$portal_name = $portal_data['name'];}else{return $this->get_current_page(CPortal::get_data(CPortal::$default), CPage::$default_page);}if($pages){foreach($pages as $page){if($page['portal'] == $portal_name){if($page['params']==''){return $page;}else{$params = explode('&',$page['params']);
						$ok = true;
						foreach($params as $param){if($param = explode('=',$param)){if(sizeof($param)==1){if(!CUrl::check($param[0])){$ok = false;
										break;}}elseif($param[0]=='portal'){if($param[1] != $portal_name){$ok = false;
										break;}}elseif(request($param[0])!=$param[1]){$ok = false;
									break;}}}if($ok){return $page;}}}}if($portal_data['parent']){return CPage::get_current_page(CPortal::get_data($portal_data['parent']), $page_name);}return reset($pages);}}static function params($key){if(isset(CPage::$current) and isset(CPage::$current->params[$key])){return CPage::$current->params[$key];}}function link($code){if(strpos($this->params['links'],$code) === false){$this->params['links'] .= $code;
			if(CPage::$drawing){echo $code;}}}function js($file){$this->link('<script type="text/javascript" src="'.$file.'"></script>');}function css($file){$this->link('<link href="'.$file.'" media="screen" rel="stylesheet" type="text/css"/>');}function region($region){$parent_id = CModule::$current?CModule::$current->id:-1;
		foreach($this->all_blocks as $id => &$block){if($block and $block->parent_id == $parent_id and $block->region == $region){$last = &CModule::$current;
				CModule::$current = &$this->all_blocks[$id];
				if(CPage::$edit_mode){echo '<li><a href="javascript:currentEditPageBlock.editClick('.$this->all_blocks[$id]->id.');">'.$this->all_blocks[$id]->name.'</a>';
					if(CFile::exists($this->all_blocks[$id]->path().'/regions.tpl')){CForm($this->all_blocks[$id]->path().'/regions.tpl')->parse($this->all_blocks[$id]->settings);}elseif(isset($this->all_blocks[$id]->data['blocks']) and $this->all_blocks[$id]->data['blocks']){$regions = array();
						foreach($this->all_blocks[$id]->data['blocks'] as &$block){$regions[isset($block['region'])?$block['region']:'center'] = 1;}$layout = '';
						foreach($regions as $region=>$nothing){$layout .= '{region(\''.$region.'\')}';}eval('?>'.CFormLayout($layout)->parse().'<?php ');}echo '</li>';}else{$this->all_blocks[$id]->draw();}CModule::$current = &$last;}}}static function get_modules_js(){$modules = array();
		$all_modules = CList(CPortal::$components)->filter(array('type'=>'MODULE'));
		foreach($all_modules as $module){$modules[$module['name']] = array(
				'path' => $module['path'],
			);}return CString($modules)->json();}}function CPage($id, $blocks = array()){return new CPage($id, $blocks);}function region($region){CPage::$current->region($region);}?><?php

class CPortal extends CRecord{static $current = false;
	static $default = 'vimua';
	static $components = array();
	static $root_url;
	static $static_url;
	static $script;
	function __construct($data){parent::__construct($data);
		if($this->setting('default-portal')){CPortal::$default = $this->setting('default-portal');}CPortal::$root_url = 'http:/'.'/'.(isset($_SERVER['HTTP_HOST'])?$_SERVER['HTTP_HOST']:'vimua.com').str_replace('index.php','',$_SERVER['SCRIPT_NAME']);
		CPortal::$static_url = $this->setting('static-url')?$this->setting('static-url'):CPortal::$root_url;}static function get_portals(){return CList(CList(CPortal::$components)->filter(array('type'=>'PORTAL')))->order('name')->items;}static function get_path($id){if(isset(CPortal::$components['PORTAL.'.$id])){return CPortal::$components['PORTAL.'.$id]['path'];}}static function get_xml_data($portal){if(!DEBUG and $data = CSystem::$cache->get('cache_portal_'.$portal['name'])){eval('$data='.$data.';');}else
		if(isset(CPortal::$components['PORTAL.'.$portal['name']])){$data = CXml(CPortal::$components['PORTAL.'.$portal['name']]['path'].'/portal.xml')->decode();
			$data['path'] = $portal['path'];
			$data['name'] = $portal['name'];
			$data['parent'] = $portal['parent'];
			$parent = trim($portal['parent']);
			if(isset(CPortal::$components['PORTAL.'.$parent])){$default_portal = CPortal::$components['PORTAL.'.$parent];
				$default_data = CPortal::get_xml_data($default_portal);
				$data = array_merge($default_data,$data);
				$data['settings'] = array_merge($default_data['settings'],$data['settings']);}CSystem::$cache->set('cache_portal_'.$portal['name'], var_export($data,1));}else{return array();}return $data;}static function get_child_portals($id){return CList(CList(CPortal::$components)->filter(array('type'=>'PORTAL','parent'=>$id)))->order('name')->items;}static function get_portal_path($id = ''){if(!$id){$id = portal()->id;}if(isset(CPortal::$components['PORTAL.'.$id]) and CPortal::$components['PORTAL.'.$id]['parent']){return '.'.$id.CPortal::get_portal_path(CPortal::$components['PORTAL.'.$id]['parent']);}else{return '.'.$id.'.';}}static function get_data($id){if(isset(CPortal::$components['PORTAL.'.$id])){return CPortal::$components['PORTAL.'.$id];}return array();}function skin($portal = false){if(!$portal){return $this->path.'/skins/default';}else{if($portal===true){$portal = CPortal::$default;}return CPortal::get_path($portal).'/skins/default';}}}function CPortal($data){return new CPortal($data);}function &portal(){return CPortal::$current;}?><?php

class CDateTime{public $time;static $date_format = 'd/m/Y';static $data_date_format = 'Y-m-d';static $date_time_format = 'd/m/Y H:i:s';static $time_format = 'H:i:s';static $remain_time_format = '%d ngày %hgiờ %iphút %sgiây';function __construct($time){if(preg_match('/^\d{4,4}\-\d{1,2}\-\d{1,2}$/', $time, $patterns)){$this->time = strtotime($time);}elseif(preg_match('/^(\d{1,2})\/(\d{1,2})\/(\d{2,4})$/', $time, $patterns) or preg_match('/^(\d{1,2})\/(\d{1,2})\/(\d{2,4})\s(\d{1,2})\:(\d{1,2})\:(\d{1,2})$/', $time, $patterns)){if(strlen($patterns[3]) == 2){if(intval($patterns[3])<50){$patterns[3] = '20'.$patterns[3];}else{$patterns[3] = '19'.$patterns[3];}}if(CDateTime::$date_format[0] == 'd'){$this->time = strtotime($patterns[2].'/'.$patterns[1].'/'.$patterns[3]);}else{$this->time = strtotime($patterns[1].'/'.$patterns[2].'/'.$patterns[3]);}if(isset($patterns[4])){$this->time += $patterns[4]*3600+$patterns[5]*60+$patterns[6];}}elseif(preg_match('/[^\d\.\s]/',$time)){$this->time = strtotime($time);}else{$this->time = $time;}}function date($format = false){return date($format?$format:CDateTime::$date_format,$this->time);}function sql_date($format = false){return date($format?$format:CDateTime::$data_date_format,$this->time);}function date_time($format = false){return date($format?$format:CDateTime::$date_time_format,$this->time);}function time($format = false){return date($format?$format:CDateTime::$time_format,$this->time);}function micro_time($format = false){return date($format?$format:CDateTime::$date_time_format,floor($this->time)).' '.($this->time - floor($this->time));}function duration($date_time){return $date_time->time - $this->time;}function elapse_time($format = false, $time = null){if($time == null){$time = time();}if(!$format){$format = CDateTime::$remain_time_format;}$remain = $time - $this->time;if($remain < 24*3600){$pos = strpos($format,'%d');$format = str_replace(substr($format,$pos,strpos($format,' ',$pos)-$pos),'',$format);}if(!($remain%60)){$pos = strpos($format,'%s');$format = str_replace(substr($format,$pos),'',$format);}if(!($remain%3600)){$pos = strpos($format,'%i');$format = str_replace(substr($format,$pos),'',$format);}if(!($remain%(24*3600))){$pos = strpos($format,'%h');$format = str_replace(substr($format,$pos),'',$format);}return str_replace(array('%d','%h','%i','%s'),array(floor($remain/(24*3600)),floor($remain/(3600))%24,floor($remain/60)%60,$remain%60),$format);}static 	function get_promotion_time(){$time_points = array(10080, 14400, 28800, 43200, 57600,72000);$this_day = getdate();$param = round(5000*sin((2*$this_day['yday']/365)*pi())) + ($this_day['year']-1984)*7 + 50*rand(0,100);foreach ($time_points as &$val){$val += $param;}return $time_points;}}function CDateTime($time){return new CDateTime($time);}?><?php

class CExpression{public $factors;public $operator;function __construct($operator = NULL, $left_factor = NULL, $right_factor = NULL){if($left_factor !== NULL){$this->factors[0] = $left_factor;}if($right_factor !== NULL){$this->factors[1] = $right_factor;}$this->operator = $operator;}public function __toString(){if(sizeof($this->factors) == 1){return $this->operator.' '.$this->factors[0];}else{$factors = array();foreach ($this->factors as $factor){$factors[] = "".$factor;}return '( '.join(' '.$this->operator.' ', $factors).' )';}}public function parse($func){if($this->factors){$factors = array();foreach ($this->factors as &$factor){if(is_object($factor)){$factors[] = $factor->parse($func);}else{if($this->operator == 'INT' or $this->operator == 'REAL'or $this->operator == 'STRING' or $this->operator == 'BOOL' or $this->operator == 'FUNCTION' or is_numeric($factor)){if($this->operator == 'INT' or $this->operator == 'REAL' or is_numeric($factor)){$factors[] = floatval($factor);}else{$factors[] = $factor;}}else{$factors[] = $factor;}}}eval('$result = '.$func.'($this->operator, $factors);');return $result;}}static function pre_process_conditions($conditions = false){if($conditions){if(is_array($conditions)){if(sizeof($conditions) == 1){foreach($conditions as $field=>$value){$expr = EEqual(EColumn($field), is_int($value)?EInt($value):EString($value));}}else{$expr = new CExpression('AND');foreach($conditions as $field=>$value){$expr->factors[] = EEqual(EColumn($field), is_int($value)?EInt($value):EString($value));}}return $expr;}elseif(is_object($conditions) and $conditions instanceof CExpression){return $conditions;}elseif(is_string($conditions)){return EColumn($conditions);}}return false;}}function EExpr($operator, $args){$expr = new CExpression($operator);foreach ($args as $arg){if($arg !== array()){if($expr->factors){if(is_string($arg) or !$arg){$expr->factors[] = EString($arg);continue;}else
				if(is_numeric($arg)){$expr->factors[] = EReal($arg);continue;}}if($arg){$expr->factors[] = CExpression::pre_process_conditions($arg);}}}return $expr;}function EAnd(){$args = func_get_args();return EExpr('AND', $args);}function EOr(){$args = func_get_args();return EExpr('OR', $args);}function ENot($left_factor){return new CExpression('!', $left_factor);}function EEqual($left_factor, $right_factor){return EExpr('=', array($left_factor, $right_factor));}function ELike($left_factor, $right_factor){return EExpr('LIKE', array($left_factor, $right_factor));}function ENLike($left_factor, $right_factor){return EExpr('NLIKE', array($left_factor, $right_factor));}function EBeginWith($left_factor, $right_factor){return EExpr('BW', array($left_factor, $right_factor));}function EEndWith($left_factor, $right_factor){return EExpr('EW', array($left_factor, $right_factor));}function EMod($left_factor, $right_factor){return EExpr('%', array($left_factor, $right_factor));}function ENE($left_factor, $right_factor){return EExpr('!=', array($left_factor, $right_factor));}function ENNULL($factor){return new CExpression('NOT_NULL', $factor);}function ENULL($factor){return new CExpression('NULL', $factor);}function EGT($left_factor, $right_factor){return EExpr('>', array($left_factor, $right_factor));}function ELT($left_factor, $right_factor){return EExpr('<', array($left_factor, $right_factor));}function EGTE($left_factor, $right_factor){return EExpr('>=', array($left_factor, $right_factor));}function ELTE($left_factor, $right_factor){return EExpr('<=', array($left_factor, $right_factor));}function EFulltextSearch($left_factor, $right_factor){return EExpr('FULLTEXT', array($left_factor, $right_factor));}function EIn($field){$expr = new CExpression('IN');$expr->factors[] = $field;$args = func_get_args();if(sizeof($args)>1 and is_array($args[1])){foreach ($args[1] as $arg){$expr->factors[] = is_int($arg)?EInt($arg):EString($arg);}}else{for ($i = 1; $i<sizeof($args); $i++){$expr->factors[] = is_int($args[$i])?EInt($args[$i]):EString($args[$i]);}}return $expr;}function EColumn($left_factor){return new CExpression('COLUMN', $left_factor);}function EId($left_factor){return new CExpression('ID', EString($left_factor));}function EString($name){return new CExpression('STRING', $name);}function EInt($name){return new CExpression('INT', $name);}function EReal($name){return new CExpression('REAL', $name);}function EBool($name){return new CExpression('BOOL', $name);}function EFunction(){$expr = new CExpression('FUNCTION');$args = func_get_args();foreach ($args as $arg){$expr->factors[] = $arg;}return $expr;}?><?php

class CList{public $items;public static $current_orders;
	function __construct($items=array()){$this->items = $items;}
	function &each($func){foreach($this->items as &$item){if($func($item)){break;}}return $this;}
	function &first(){return reset($this->items);}
	function next(){return next($this->items);}function json(){return json_encode($this->items);}
	function flatten($key = false){$items = array();foreach($this->items as $id=>&$item){if(!$key){$key = isset($item['name'])?'name':
						(isset($item['title'])?'title':
						 (isset($item['id'])?'id':false));}if($key and isset($item[$key])){$items[$id] = $item[$key];}}return $items;}
	function filter($conditions){$new_items = array();if(is_array($this->items)){foreach($this->items as $id=>&$item){if(is_array($conditions)){if(CRecord($item)->test($conditions)){$new_items[$id] = $item;}}elseif(!$conditions){$new_items[$id] = $item;}elseif(is_array($item)){if(isset($item['id']) and $item['id'] == $conditions){$new_items[$id] = $item;}}elseif($item == $conditions){$new_items[$id] = $item;}}}return $new_items;}
	function &order($order_by){CList::$current_orders = explode(',', $order_by);foreach(CList::$current_orders as $i => $order){$dir = 'ASC';if(strpos($order, 'DESC') or strpos($order, 'desc')){$dir = 'DESC';}$order = trim(str_ireplace(array(' ASC', ' DESC'), array('', ''),$order));CList::$current_orders[$i] = array($order, $dir);}uasort($this->items, 'item_compare');return $this;}
	function extract_id($field){$items = array();foreach($this->items as &$item){if(isset($item[$field])){$items[$item[$field]] = $item;}}return $items;}
	function group($field){$groups = array();foreach($this->items as &$item){if(isset($item[$field])){if(!isset($groups[$item[$field]])){$groups[$item[$field]] = array();}if(isset($item['id'])){$groups[$item[$field]][$item['id']] = $item;}else{$groups[$item[$field]][] = $item;}}}return $groups;}}function CList($items = array()){return new CList($items);}function item_compare($a, $b){foreach(CList::$current_orders as $order){if(isset($a[$order[0]]) and isset($b[$order[0]])){if(is_numeric($a[$order[0]]) and is_numeric($b[$order[0]])){$compare = number_format($a[$order[0]] - $b[$order[0]]);}else{$compare = strcmp($a[$order[0]], $b[$order[0]]);}if($order[1] == 'DESC'){$compare = - $compare;}if($compare != 0){return $compare;}}}return 0;}?><?php

class CNumber{public $value = 0;static $thousand_separator = '.';static $decimal_separator = ',';function __construct($value){$this->value = $value;}
	function value($decimals=false){return number_format($this->value,$decimals,CNumber::$decimal_separator,CNumber::$thousand_separator);}function __to_string(){return $this->value();}function number(){return str_replace(array('.',','),array('','.'),$this->value);}function price(){return str_replace(',00','',number_format($this->value,2,',','.'));}}function CNumber($value){return new CNumber($value);}?><?php

class CRecord{public $data;
	
	function __construct($data=array()){if(is_object($data) and ($data instanceof CTable)){if($data->record){$this->data = $data->record->data;}}else{$this->data = $data;}}
    public function __get($name){if (isset($this->data[$name])){return $this->data[$name];}elseif(isset($this->$name)){return $this->$name;}return false;}
    public function __set($name, $val){if (isset($this->$name)){$this->$name = $val;}else{$this->data[$name] = $val;}}
    public function __isset($name){return isset($this->$name)?true:isset($this->data[$name]);}
    public function __unset($name){unset($this->data[$name]);}public function test($conditions){if($conditions and is_array($conditions)){foreach($conditions as $key=>$value){if(is_array($this->data)){if(!isset($this->data[$key]) or $this->data[$key] != $value){return false;}}elseif(is_object($this->data)){if(!isset($this->data->$key) or $this->data->$key != $value){return false;}}}}if($conditions and is_object($conditions)){switch ($conditions->operator){case 'ID':
					if($conditions->factors[0] != $this->id){return false;}break;
				case 'AND':
					foreach($conditions->factors as $factor){if(!$this->test($factor)){return false;}}break;
				case 'OR':
					foreach($conditions->factors as $factor){if($this->test($factor)){return true;}}break;
				case '!':
					return !$this->test_value($conditions->factors[0]);
				default:
					if(sizeof($conditions->factors)>1){$left = $this->test_value($conditions->factors[0]);
						$right = $this->test_value($conditions->factors[1]);
						eval('$ok = '.$left.' '.$conditions->operator.' '.$right.';');
						return $ok;}break;}}return true;}
    function test_value($expr){if(is_string($expr)){if(isset($this->data[$expr])){return $this->data[$expr];}}elseif(is_object($expr)){switch ($conditions->operator){case 'STRING':
				case 'INT':
				case 'FLOAT':
				case 'BOOL':
					return $conditions->factors[0];}}}function  setting($name, $default = false){return isset($this->settings[$name])?$this->settings[$name]:$default;}function set_setting($name, $value){$this->settings[$name] = $value;}}
function CRecord($data = array()){return new CRecord($data);}?><?php

class CString{public $value = 0;static $allowedTags = '<h1><b><i><a><ul><li><pre><hr><blockquote><img>';
	static $stripAttrib = 'javascript:|onclick|ondblclick|onmousedown|onmouseup|onmouseover|onmousemove|onmouseout|onkeypress|onkeydown|onkeyup';function __construct($value){$this->value = $value;}
	function removeEvilTags(){$source = strip_tags($this->value, CString::$allowedTags);return preg_replace('/<(.*?)>/ie', "'<'.removeEvilAttributes('\\1').'>'", $source);}function js_string(){return str_replace(array("'",'"',"\n"), array('&lsquo;','&quot;', '\\n'), $this->value);}function json(){return json_encode($this->value);}function lining(){$lines = split("\n",$this->value);$value = '<ol>';foreach($lines as $i => $line){$value .= '<li>'.str_replace("\r",'',$line)."</li>";}return $value.'</ol>';}function explode($separator, $index){$array_result= explode($separator, $this->value);return $array_result[$index];}function get_image_name(){$pattern = explode('/', $this->value);$count = count($pattern);return $pattern[$count-1];}function get_last_name($separator){$pattern = explode($separator, $this->value);$count = count($pattern);return $pattern[$count-1];}function search_keyword(){$search_hightlight = array();$st=$this->value;$st=strtr($st,"Ã ","ÃÃ");$st=strtr($st," ","+");$st=strtr($st,"|"," ");$count=0;$result="";for($i=0;$i<strlen($st);$i++){if($st[$i]=='"'){$count++;if($count%2)$result.='+';}$result.=$st[$i];}$st=$result;while(preg_match('/"([^\"]*)"/',$st,$a)){$search_hightlight[]=strtr($a[1],array("+"=>"\s+","ÃÃ"=>"Ã "));$st=strtr($st,array($a[0]=>" "));$result=strtr($result,array($a[0]=>strtr($a[0],array("+"=>" "))));}while(preg_match('/[^+\s-]+/',$st,$a)){$search_hightlight[]=strtr($a[0],array("ÃÃ"=>"Ã "));$st=strtr($st,array($a[0]=>" "));}$result=preg_replace("/([+|])/"," \\1",$result);if($result[0]!='-')$result="+".$result;$this->high_light = $search_hightlight;$this->value = strtr($result,array("ÃÃ"=>"Ã "));return $this->value;}function hightlight_keyword($keywords){if($keywords){$value = strtolower($keywords);$this->value = preg_replace(array('/^('.$value.')([^\w])/i','/([^\w])('.$value.')([^\w])/i'), array("<strong><span style='background-color:yellow;color:black'>\\1</span></strong>\\2","\\1<strong><span style='background-color:yellow;color:black'>\\2</span></strong>\\3"), $this->value);}return $this->value;}function get_tags(){require_once 'lib/utils/CVNCode.php';$keywords = strtolower(strip_tags($this->value));$keywords .= ' '.CVNCode::convert_utf8_to_latin($keywords);return CString($keywords)->extend_search_keyword();}function extend_search_keyword(){$keywords = strtolower(strip_tags($this->value));if($words = preg_split('/([^\w]+)/',$keywords,-1,PREG_SPLIT_DELIM_CAPTURE)){$keywords = '';foreach($words as $i => $word){$keywords .= $word;if($i%2==0 and $word){$end_char = $word{strlen($word)-1};if(strlen($word) < 4 and (is_numeric($end_char) or 
						(ord($end_char)>=ord('a') and ord($end_char)<=ord('z')) or $end_char=='_')){$keywords .= 'kjfs';}}}}$this->value = $keywords;$this->highlight = array();$this->search_keyword();return $this->value;}}function CString($value){return new CString($value);}function json($st){return json_encode($st);}function js_string($st){return CString($st)->js_string();}
function removeEvilAttributes($tagSource){return stripslashes(preg_replace('/'.CString::$stripAttrib.'/i', 'forbidden', $tagSource));}?><?php
class COutput{function __construct(){ob_start();}function get($expression){return ob_get_clean();}function ceval($expression){return eval('?>'.$expression.'<?php ');}}function output(){return new COutput();}?><?php
class CSession{static $current;
	public $id;
	function __construct(){session_start();
		setcookie("PHPSESSID", session_id(), 0, "/", COOKIE_URL); 
		$this->id = session_id();}function get($name){if(isset($_SESSION[$name])){return $_SESSION[$name];}}function set($name, $value){$_SESSION[$name] = $value;}function delete($name){unset($_SESSION[$name]);}function close(){}}function session($name = false, $value = NULL){if($name){if($value === NULL){$value = CSession::$current->get($name);}else{CSession::$current->set($name, $value);}return $value;}return CSession::$current;}function cookie($name, $value = NULL){if($value === NULL){return isset($_COOKIE[$name])?$_COOKIE[$name]:'';}else{return setcookie($name, $value, time()+3600, '/',COOKIE_URL);}}?><?php

class CSystem{static $cache;
	static function start(){if(request('url_mode') == 'ajax'){CUrl::$mode = 'ajax';}if(DEBUG){require_once 'lib/utils/CLog.php';
			error_reporting(E_ALL | E_STRICT | E_NOTICE);}else{error_reporting(E_ALL);}if(DEBUG){CLog('SYSTEM','Start up!');}CSystem::init_cache();
		if(DEBUG or !($component_cache = CSystem::$cache->get('CPortal::$components'))){require_once 'lib/utils/CComponent.php';
			$component_cache = CComponent::make_component_cache();}eval(' ?>'.$component_cache.'<?php ');
		CSystem::init_portal();
		if(portal()->setting('default-portal')){CPortal::$default = portal()->setting('default-portal');}if(!portal()->setting('no-ftp') and $ftp = portal()->setting('ftp')){define('USE_FTP',true);
			define('FTP_USER',$ftp['user']);
			define('FTP_PASSWORD',$ftp['password']);
			define('FTP_HOST',$ftp['host']);
			define('FTP_PREFIX','ftp://'.FTP_USER.':'.FTP_PASSWORD.'@'.FTP_HOST.'/');
			define('FILE_SERVER_URL',$ftp['file-server-url']);
			define('HTTP_RESOURCE',$ftp['http-resource']);}else{define('USE_FTP',false);
			define('FTP_USER','');
			define('FTP_PASSWORD','');
			define('FTP_HOST','');
			define('FTP_PREFIX','');
			define('FILE_SERVER_URL','');
			define('HTTP_RESOURCE','');}if($image_settings = portal()->setting('image_settings')){define('ASIDO_GD_JPEG_QUALITY',$image_settings['jpeg-quality']);
			define('THUMB_WIDTH',$image_settings['thumb-width']);
			define('THUMB_HEIGHT',$image_settings['thumb-height']);}if(defined('MASTER_DATABASE_HOST')){$database = array(
				'host'=>constant('MASTER_DATABASE_HOST'),
				'user'=>constant('MASTER_DATABASE_USER'),
				'password'=>constant('MASTER_DATABASE_PASSWORD'),
				'database-name'=>constant('MASTER_DATABASE_NAME'),
				'slave-host'=>constant('SLAVE_DATABASE_HOST'),
				'slave-user'=>constant('SLAVE_DATABASE_USER'),
				'slave-password'=>constant('SLAVE_DATABASE_PASSWORD'),
				'slave-database-name'=>constant('SLAVE_DATABASE_NAME'),
			);}else{$database = portal()->settings['database'];}if(!isset($database['slave-host'])){if(isset($database['slaves']) and is_array($database['slaves']) and $slaves_count = sizeof($database['slaves'])>0){if($slaves_count == 1){$i = 'slave';}else{srand(time());
					$i = rand(0, $slaves_count - 1);}$database['slave-host'] = $database['slaves'][$i]['host'];
				$database['slave-user'] = $database['slaves'][$i]['user'];
				$database['slave-password'] = $database['slaves'][$i]['password'];
				$database['slave-database-name'] = $database['slaves'][$i]['database-name'];}else{$database['slave-host'] = false;
				$database['slave-user'] = false;
				$database['slave-password'] = false;
				$database['slave-database-name'] = false;}}CStore::$default = new CMySQLStore(
			$database['host'],
			$database['user'],
			$database['password'],
			$database['database-name'],
			$database['slave-host'],
			$database['slave-user'],
			$database['slave-password'],
			$database['slave-database-name']
		);
		if(portal()->setting('session') == 'database'){CSession::$current = new CSession();}else{CSession::$current = new CSession();}CLanguage::$current = new CLanguage(session('language',portal()->setting('language')));
		if(session('user_id')){if(!isset($_COOKIE['userId']) or session('user_id') != $_COOKIE['userId']){setcookie('userId',session('user_id'), time()+3600, '/','.vimua.com');}CUser::$current = new CUser(session('user_id'));}else
		if(cookie('saved_password') and request('page')!='sign_in'){redirect('sign_in', array('href'=>'/?'.$_SERVER['QUERY_STRING']));}else{if(isset($_COOKIE['userId'])){setcookie('userId', 'guest', time()+3600, '/','.vimua.com');
				setcookie('shopping-cart-total-items', 0, time()+3600, '/','.vimua.com');}CUser::$current = new CUser(array('id'=>'guest'));}}static function init_portal(){if(isset(CPortal::$components['PORTAL.'.request('portal', CPortal::$default)])){$portal = CPortal::$components['PORTAL.'.request('portal', CPortal::$default)];}else{$portal = CPortal::$components['PORTAL.'.CPortal::$default];}CPortal::$current = CPortal(CPortal::get_xml_data($portal));}static function end(){if(DEBUG){CLog('SYSTEM','Shut down!');
			CLog()->show();}if(CFile::$ftp_connection_id){ftp_close(CFile::$ftp_connection_id);}exit();}static function init_cache(){if(function_exists('memcache_connect')){CSystem::$cache = new CMemCache(($memcache = $GLOBALS['memcache'])?$memcache:array(array('host'=>'localhost')));
			if(!CSystem::$cache->connected_servers){CSystem::$cache = new CCache();}}else{CSystem::$cache = new CCache();}}static function using($name){$components = explode('.',$name);
		$file_name = '';
		for($i=0; $i<sizeof($components)-1; $i++){$file_name .= 'packages/'.$components[$i].'/';}require_once($file_name.'modules/'.$components[$i].'/class.php');}}function using($name){CSystem::using($name);}?><?php
class CUser extends CRecord{static $current = false;
	public $module_privileges = array();
	public $privileges = array();
	static $all_privileges = false;
	public $store;
	public $email;
	function __construct($data){if(is_array($data) or is_object($data)){parent::__construct($data);}else{$this->id = $data;
			if(portal()->setting('export-user')){$cache_file = CUser::cache_file($this->id);
				if(DEBUG or !($exists = CFile::exists($cache_file))){if($user = CUser::create_cache_file($this->id, $this)){parent::__construct($user);}}else{$this->store = CXmlStore($cache_file, '/root/');
					parent::__construct($this->table('user/user-info')->select());
					$this->module_privileges = $this->table('user/module-privileges')->select();
					$this->privileges = $this->table('user/privileges')->select();}}else{if($user = CTable('user')->select($this->id)){if(DEBUG or !$user['privilege_cache']){$new_record = CUser::update_cache($user['id']);
						$user['privilege_cache'] = $new_record['privilege_cache'];
						$user['privileges'] = $new_record['privileges'];}eval('$this->module_privileges = '.$user['privilege_cache'].';');
					eval('$this->privileges = '.$user['privileges'].';');
					unset($user['privilege_cache']);
					unset($user['privileges']);
					$this->email = $user['email'];
					unset($user['email']);
					unset($user['password']);
					parent::__construct($user);}}}}static function create_cache_file($user_id, &$that){$cache_file = CUser::cache_file($user_id);
		if(CFile::exists($cache_file)){$old_store = CXmlStore($cache_file, '/root/');
			$shopping_cart = CTable('user/shopping-cart/product')->change_store($old_store)->select_all();
			$wish_list = CTable('user/wish-list/product')->change_store($old_store)->select_all();}else{$shopping_cart = array();
			$wish_list = array();}file_put_contents($cache_file,'<?xml version="1.0" encoding="utf-8"?>
<root><user></user></root>');
		if($user = CTable('user')->select($user_id)){if($user_id == $that->id){$that->store = CXmlStore($cache_file, '/root/');
				$store = &$that->store;
				$that->email = $user['email'];}else{$store = CXmlStore($cache_file, '/root/');}unset($user['password']);
			unset($user['email']);
			if(DEBUG or !$user['privilege_cache']){$new_record = CUser::update_cache($user['id']);
				$user['privilege_cache'] = $new_record['privilege_cache'];
				$user['privileges'] = $new_record['privileges'];}eval('$module_privileges = '.$user['privilege_cache'].';');
			eval('$privileges = '.$user['privileges'].';');
			if(!$wish_list){if(isset($user['wishlist']) and $user['wishlist']){eval('$wishlist = '.$user['wishlist'].';');}else{$wishlist = array();}}unset($user['privilege_cache']);
			unset($user['wishlist']);
			unset($user['privileges']);
			CTable('user')->change_store($store)->update(array(
				'user-info'=>$user,
				'privileges'=>$privileges,
				'module-privileges'=>$module_privileges,
				'wish-list' => array(),
				'shopping-cart' => array(),
			));
			if($shopping_cart){$store->insert_list('user/shopping-cart/product', $shopping_cart);}if($wish_list){$store->insert_list('user/wish-list/product', $wish_list);}if($user_id == $that->id){$that->shopping_cart = $shopping_cart;
				$that->wishlist = $wishlist;
				$that->privileges = $privileges;
				$that->module_privileges = $module_privileges;}return $user;}}static function cache_file($user_id){$dir = 'publish/'.CPortal::$default.'/user/'.substr($user_id,0,2);
		CFile($dir)->mkdir();
		return $dir.'/'.$user_id.'.xml';}function recache($user_id = false){if(portal()->setting('export-user')){CUser::create_cache_file($user_id?$user_id:$this->id, $this);}}function wishlist($items = false){if($items !== false){if(user()->id){CTable('user')->update(array('wishlist'=>var_export($items,1)), $this->id);}}else{if(isset($this->wishlist) and $this->wishlist){eval('$wishlist = '.$this->wishlist.';');
				return $wishlist;}}return array();}function shopping_cart($items = false){if($items !== false){session('cart',$items);	
			/*if(user()->id){CTable('user')->update(array('shopping_cart'=>var_export($items,1)), $this->id);
				$this->shopping_cart = var_export($items, 1);}*/}else{if($shopping_cart = session('cart')){if(is_string($shopping_cart)){eval('$shopping_cart = '.$shopping_cart.';');}return $shopping_cart;}/*
			if($shopping_cart = session('cart') and user()->is_login()){if(is_string($shopping_cart)){eval('$shopping_cart = '.$shopping_cart.';');}if($shopping_cart){$this->shopping_cart($shopping_cart);
					session('cart', array());
					return $shopping_cart;}}if(isset($this->shopping_cart) and $this->shopping_cart){eval('$shopping_cart = '.$this->shopping_cart.';');
				return $shopping_cart;}*/}return array();}function table($path){return CTable($path)->change_store($this->store);}static function encode_password($password){return md5($password.'vinbuy2008');}function is_login(){return session('user_id');}function is_admin(){return isset($this->privileges[CPortal::$default]['Administrators']) or isset($this->privileges['default']['Administrators']) or isset($this->privileges[portal()->id]['Administrators']);}function can_do_action($pos,$module_id=false, $parameters = 0){if($this->is_admin()){return true;}if(!$module_id){if(module()){$module_id = module()->name;}else{$module_id=false;}}if(!$module_id){return;}if(isset($this->module_privileges[CPortal::$current->id])){{if(isset($this->module_privileges[CPortal::$current->id][$module_id])){if($this->module_privileges[CPortal::$current->id][$module_id]&(1 << $pos)){return true;}}}}}function can_view($module_id=false, $category_id = 0){return $this->can_do_action(0,$module_id, $category_id);}function can_view_detail($module_id=false, $category_id = 0){return $this->can_do_action(1,$module_id, $category_id);}function can_add($module_id=false, $category_id = 0){return $this->can_do_action(2,$module_id, $category_id);}function can_edit($module_id=false, $category_id = 0){return $this->can_do_action(3,$module_id, $category_id);}function can_delete($module_id=false, $category_id = 0){return $this->can_do_action(4,$module_id, $category_id);}function can_moderator($module_id=false, $category_id = 0){return $this->can_do_action(5,$module_id, $category_id);}function can_developer($module_id=false, $category_id = 0){return $this->can_do_action(6,$module_id, $category_id);}function can_admin($module_id=false, $category_id = 0){return $this->can_do_action(7,$module_id, $category_id);}static function get_child_privileges($portal_id, &$all_privileges, $privilege_id, $values){if(!CUser::$all_privileges){CUser::$all_privileges = CTable('privilege')->select_all();}if($privileges = CList(CUser::$all_privileges)->filter(array('parent_id' => $privilege_id))){foreach($privileges as $privilege){if(!isset($all_privileges[$portal_id][$privilege['id']])){$all_privileges[$portal_id][$privilege['id']] = $values;
					CUser::get_child_privileges($portal_id, $all_privileges, $privilege['id'], $values);}}}}static function privilege_cache($user_id, &$all_privileges){$privileges = array();
		$all_privileges = array();
		if($user_privileges = CTable('user_privilege')->select_all(array('user_id'=>$user_id))){foreach($user_privileges as $user_privilege){if(!isset($all_privileges[$user_privilege['portal_id']])){$all_privileges[$user_privilege['portal_id']] = array();}$values = 1;
				if($categories = CTable('privilege_category')->select_all(array(
					'user_id' => $user_id,
					'portal_id' => $user_privilege['portal_id'],
					'privilege_id' => $user_privilege['privilege_id']
				))){$values = array();
					foreach($categories as $category){$values[$category['category_id']] = 2;}}$all_privileges[$user_privilege['portal_id']][$user_privilege['privilege_id']] = $values;
				CUser::get_child_privileges($user_privilege['portal_id'], $all_privileges, $user_privilege['privilege_id'], $values);
				if(!isset($privileges[$user_privilege['portal_id']])){$privileges[$user_privilege['portal_id']] = array();}/*if(!isset($privileges[$user_privilege['portal_id']][$user_privilege['parameters']])){$privileges[$user_privilege['portal_id']][$user_privilege['parameters']] = array();}*/
				if($modules = CTable('privilege_scope')->select_all(array('privilege_id'=>$user_privilege['privilege_id']))){foreach($modules as $module){$privileges[$user_privilege['portal_id']][$module['module']] = bindec($module['can_admin'].$module['can_developer'].$module['can_moderator'].$module['can_delete'].$module['can_edit'].$module['can_add'].$module['can_view_detail'].$module['can_view']);}}}}if($user_groups = CTable('user_group')->select_all(array('user_id'=>$user_id))){foreach($user_groups as $user_group){if(isset($user_group['group_id']) and $group = CTable('user')->select(array('id'=>$user_group['group_id']))){if(!$group['privileges']){$group_all_privileges = array();
						$group_privileges = CUser::privilege_cache($user_group['group_id'], $group_all_privileges);}else{eval('$group_all_privileges = '.$group['privileges'].';');
						eval('$group_privileges = '.$group['privilege_cache'].';');}$privileges = array_merge_recursive($group_privileges, $privileges);
					$all_privileges = array_merge_recursive($group_all_privileges, $all_privileges);}}}return var_export($privileges,1);}static function update_cache($user_id){if($user_id){$record = array('privilege_cache'=>CUser::privilege_cache($user_id,$all_privileges), 'privileges'=>var_export($all_privileges,1));
			CTable('user')->update($record, $user_id);
			return $record;}}static function flush_privilege_cache(){CTable('user')->update(array('privilege_cache'=>'', 'privileges'=>''), false);
		if(portal()->setting('export-user')){CFile('publish/'.CPortal::$default.'/user')->delete();}}function save_privilege_cache(){$table = CTable('privilege')->change_store(CXmlStore('users/admin.xml', '/root/'));}function update_online_status($status = 1, $module = false){if(user()->is_login()){$table = CTable('user_online');
			if($status == 0){$table->delete(user()->id);}else{$chat_windows = 0;
				if(CPortal::$default == 'vimua'){$chat_windows = session('chat_windows');}if($table->select(user()->id)){$table->update(array('id'=>user()->id,
						'time'=>time(),
						'time_out'=>time()+5*60,
						'module'=>$module?$module:module()->name,
						'chat_windows' => $chat_windows,
						'is_seller' => (isset(user()->is_register_salesman) and user()->is_register_salesman == 2)?1:0,
					),user()->id);}else{$table->save(array(
						'id'=>user()->id,
						'time'=>time(),
						'time_out'=>time()+15*60,
						'module'=>$module?$module:module()->name,
						'chat_windows' => $chat_windows,
						'seller_point'=>user()->seller_point,
						'buyer_point'=>user()->buyer_point,
						'avatar'=>user()->avatar_url,
						'blast'=>user()->blast,
						'is_seller' => (isset(user()->is_register_salesman) and user()->is_register_salesman == 2)?1:0,
					),user()->id);}}session('last_online_time',time());}}function has_privilege($privilege){return user()->is_admin() or (isset($this->privileges[portal()->id]) and isset($this->privileges[portal()->id][$privilege]));}}function &user(){return CUser::$current;}?><?php CSystem::start();?>